Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Rails 3 question: How to sort products?

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?

like image 976
Misha Moroshko Avatar asked Dec 02 '25 08:12

Misha Moroshko


1 Answers

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")
like image 192
iain Avatar answered Dec 04 '25 00:12

iain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!