rails find(params[:id]) 总是 returns 第一个元素的 id

rails find(params[:id]) always returns id of the first element

我正在尝试获取条目的用户 ID 并 return 它在文档显示视图中

documents_controller.rb

def show
    @document = Document.find(params[:id])
    @entries = @document.entries  # to show all entries of a document
    @user = Entry.find(params[:id]).user_id # trying to get id of the user that was selected in the entry (always returns id of the first entry of a document)
end

documents/show.html.erb

<% @entries.each do |document| %>
    <tr>
        <% userName = @user%>
        <td><%= userName %></td> //always gets same id
        <% #end %>
    </tr>
<% end %>

如果 Entry 有一个 user_id 列,那么只需在循环中打印它:

<% @entries.each do |document| %>
  <tr>
    <td>User id: <%= document.user_id %></td>

    <!-- if you're looking for the users name, I'd say you will be using: -->
    <td>User name: <%= User.find(document.user_id).name %></td>
  </tr>
<% end %>

使用 Entry.find(params[:id]).user_id 你只能找到那个 user_id 因为你是由 params[:id] 找到它的,这在循环中总是相同的。