aschmid aschmid - 3 months ago 25
Ruby Question

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

I am trying to get the id of the user of the entry and return it in the documents show view

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 %>

Answer

If Entry has a user_id column, then just print it in the loop:

<% @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 %>

With Entry.find(params[:id]).user_id you were only finding that one user_id because you were find it by params[:id], which was always the same in the loop.

Comments