问题
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?
回答1:
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")
回答2:
See this article: http://www.definenull.com/node/8
In your example:
@products = Product.find(:all,:include => [:shop, :brand], :order => 'shops.name ASC, brands.name ASC')
I haven't tested this code myself so I can't vouch for it 100% but give it a try. If it dosent work try removing the "ASC" and see if that runs.
来源:https://stackoverflow.com/questions/4416106/basic-rails-3-question-how-to-sort-products