Learning Rails, how to walk through relations in template?

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

Please look into this
http://apidock.com/rails/ActiveRecord/QueryMethods/includes

As described here
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

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.

Thank you, got it working.

On 16 September 2014 18:22, frocco [email protected] wrote:

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?

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