aschmid aschmid - 1 year ago 86
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 %>

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download