0

I have this in the index view:

<% @submissions.each do |submission| %>
    <tr>
        <td><%= submission.id %></td>
        <td><%= User.find_by_id(submission.user_id).name.to_s %></td>
    </tr>
<% end %>

I know I am not supposed to use find_by in the view.

How can I move this to the controller (or model)?

I tried to insert this in the index method of my submission controller and using the username variable but it doesn't work.

def index
    @submissions = Submission.all
    @submissions.each do |submission|
      username = User.find_by_id(submission.user_id).name.to_s
    end
end
1
  • You have a N+1 problem Commented Feb 27, 2013 at 23:52

3 Answers 3

3

Model, add relation to user

class Submission
  belongs_to :user
end

Controller, eager load users to avoid N+1 queries.

def index
  @submissions = Submission.includes(:user).all
end

View, just project the user from each submission

<% @submissions.each do |submission| %>
    <tr>
        <td><%= submission.id %></td>
        <td><%= submission.user.name.to_s %></td>
    </tr>
<% end %>
Sign up to request clarification or add additional context in comments.

4 Comments

Can I also use this approach on another model type when submission has_many types?
Yes, you can. In that case you will have many 'types', and you will need iterate them.
Thank you, in my case, I just use submission has_one type since I only have one type for each submission. Another question though: my submission model belongs_to another model base, but the base model uses a different table name self.table_name = submission_bases. When I try to do the something like user, it doesn't work anymore, in my view I used submission.base but it cannot recognize the model base. In my submissions table I have a foreign key submission_base_id
Never mind, I found the problem: need to set: belongs_to :base, :foreign_key => :submission_base_id
2
#in controller
def index
  @submissions = Submission.all
end

#in view
<% @submissions.each do |submission| %>
    <tr>
        <td><%= submission.id %></td>
        <td><%= submission.user.name %></td>
    </tr>
<% end %>

This code implies you have declared the following relations:

  • Submission belongs_to :user
  • User has_many :submissions (or has_one)

You can use eager loading (uses less queries to the DB) to improve the previous code:

@submissions = Submission.includes(:user).all

Comments

0

You can use an ActiveRecord association:

class Submission
  belongs_to :user

  # etc
end

Then in your view:

<td><%= submission.id %></td>
<td><%= submission.user.first_name</td> <!-- or whatever -->

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.