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
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
As described here
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs