views:

43

answers:

1

I have a Vendor controller for show:

def show
@vendor = Vendor.find(params[:id])

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @vendor }
end
end

In my View for Reviews (where Vendor :has_many Reviews)

 <% if @vendor.reviews.empty? %>
  No Analyst Reports yet
 <% else %>
  <% for review in @vendor.reviews %>

   <%= review.user_id %>
   <%= review.summary %><br />
   <hr class="span-5" />

  <% end %>
 <% end %>

So I am basically going through a 'for' loop for all the reviews for a particular vendor (this has been a tricky concept for me but it seems to work).

So: I want to display the User.name and user.email. I know what the user_id for each corresponding Review is (review.user_id) but I don't know how to display values for the User model.

I thought using find_by_id would work but it doesn't recognize User.

Help?

+1  A: 

If you've set up a :has_one relationship between the Review model and the User model, then you can just use review.user to access it. So you'd get user attributes with review.user.name, review.user.email, etc.

Note that if you're going to be retrieving many child records to loop through like this, you may want to call find with an :include parameter to reduce the number of queries made. Something like:

Vendor.find(params[:id], :include => { :reviews => :user } )

See the API docs for has_one for more info.

Andrew Watt
Hi, would I include the Vendor.find within the for-loop? I created a ':has_many' relationship because a user has_many reviews. Is that possible?
Angela
No, you don't need to call find more than once. Just add ":belongs_to :user" to your Review model to make their relationship work both ways.
Andrew Watt
yes, I already have a :belongs_to and review.user.name keeps saying that the value is 'nil'....let me play around with it.
Angela
I figured it out...thank you!
Angela
what does the :include => mean, will API docs explain that? Thanks...
Angela
It means to preload all the reviews and users at the same time as the vendor, which is faster than letting them load one-by-one as needed. On the same documentation page I linked, the section above entitled "Eager loading of associations" explains it.
Andrew Watt