aschmid aschmid - 6 months ago 40
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


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)


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


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

<% @entries.each do |document| %>
    <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>
<% 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.