I have the following models:
Product: name, shop_id (foreign key), brand_id (foreign key), price
Shop: name
Brand: name
The associations are:
Product: belongs_to :shop
belongs_to :brand
Shop: has_many :products
has_many :brands, :through => :products
Brand: has_many :products
has_many :shops, :through => :products
In ProductsController#list I would like to get a list of all products sorted by shop name and then by brand name.
I tried to do:
@products = Product.order("products.shop.name ASC, products.brand.name ASC")
But it doesn't work (I guess because products.shop.name does not exist at the database level).
What is the right way to do this?
Austin L is right, but his syntax is a bit old. The new ActiveRecord syntax is much cleaner:
@products = Product.includes(:shop, :brand).order("shops.name ASC, brands.name ASC")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With