"Couldn't find User without an ID" 访问相关模型

"Couldn't find User without an ID" accessing related model

更新问题:

我正在尝试访问 class 实例的 ID 并使用它来查找该实例。这是上下文:

  <% @affinity.each do |a| %>
    <tr>
      <td><%= a.user_A_id %></td>
      <td><%= User.find(a.user_A_id).nickname %></td>
      <td><%= a.user_B_id %></td>
      <td><%= User.find(a.user_B_id).nickname %></td>
      ...

每个affinity都有一个名为User_A_idUser_B_id的变量,代表用户A和B的ID。我想使用这些ID来访问实例用户 A 和用户 B,随后是每个用户的 nickname。我该怎么做?

我目前收到此错误:

Couldn't find User without an ID

谢谢!

如果您定义了正确的关系,您可以直接访问这些用户:

<%= a.user_A.nickname %>

顺便说一句,您不必将这些 ID 转换为符号即可使该代码正常工作,并且您可以使用 User.find(a.user_A_id) 因为 where returns 一个数组和 find returns 找到的对象。