Learning Rails, how to walk through relations in template?

35 views
Skip to first unread message

frocco

unread,
Sep 16, 2014, 1:22:33 PM9/16/14
to rubyonra...@googlegroups.com
Hello,

I have a products table that is related to category.

category has many products.

How do I query the products to also include the category?

Once I do this, how to I show the category data in my template?

Thanks

Vivek Sampara

unread,
Sep 16, 2014, 1:27:27 PM9/16/14
to rubyonra...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/ef128a6d-5b7b-412f-b8ca-db77ccbff2c2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jason Fleetwood-Boldt

unread,
Sep 16, 2014, 1:31:09 PM9/16/14
to rubyonra...@googlegroups.com

I think what you want is something like

products = Product.includes(:category)

This will eager load the category association when you load the Product objects. You must specify the inverse relationship (in product.rb you must have belongs_to :category) for this to work.



frocco

unread,
Sep 16, 2014, 1:39:55 PM9/16/14
to rubyonra...@googlegroups.com
Thank you, got it working.

Colin Law

unread,
Sep 16, 2014, 3:27:07 PM9/16/14
to rubyonra...@googlegroups.com
There is usually no need to ask for the products to include the
category. If, for example, you say
@products = Product.where some_condition

then in your template (or in the controller) you can use code such as
@products.first.category even though you have not specifically used
.includes in the query. Rails will fetch the category later if it is
needed.

Colin
Reply all
Reply to author
Forward
0 new messages