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?
-
If you've set up a
:has_onerelationship between the Review model and the User model, then you can just usereview.userto access it. So you'd get user attributes withreview.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
findwith an:includeparameter 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.
Angela : 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?Andrew Watt : 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.Angela : 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...Andrew Watt : 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.
0 comments:
Post a Comment