Riding Rails
Riding Rails

Reputation: 23

Finding user object in view? Ruby on Rails

    <% @review.each do |review|%>
    <% if review.host_id == @host.id> 
       <%= @user = User.find(review.user_id) %>
    <% end %>
<% end %>   

So I'm a bit confused. I have a few things going on here. I'm doing a loop through all reviews of hosts and then checking if the stored host.id value is equal to the active @host object's id that is passed from the controller. Problem is.. Now I need get the user object from the user ID stored in the review but, I'm unsure exactly how to do it. I can't do it from the controller as all this is done in the loop. As you can see I tried to do it with the code above but, I highly doubt I did it right. Please help me out on this. Thanks.

Upvotes: 0

Views: 138

Answers (3)

Marek Lipka
Marek Lipka

Reputation: 51151

You should pre-load users with loading reviews, in controller. First, you should have belongs_to association, like this:

class Review < ActiveRecord::Base
  belongs_to :user
  # ...
end

then, in controller, you could use includes, this way:

@reviews = Review.includes(:user)

Now, for every review record in @reviews relation, to get associated user you can call user method, like this:

review.user

What's more, (and that's advantage of using includes) it doesn't fire new SQL query for every single review, so you avoid quite common N + 1 problem.

Upvotes: 1

Allerin
Allerin

Reputation: 1108

Put association in Review Model

class Review < ActiveRecord::Base

.
.
.
  belongs_to :user
.
.
.

end

After putting association you can directly call association to find user object using Review object.

review.user

But this will raise N+1 query problem, so better user include user while finding review, It will execute only two queries one for finding reviews and another for finding users.

@reviews = Review.includes(:user)

Upvotes: 0

techvineet
techvineet

Reputation: 5111

You can make a relationship in

class Review < ActiveRecord::Base
belongs_to :user
end

and then in view

review.user #gives you user

Upvotes: 0

Related Questions