Basic Rails 3 question: How to sort products?

我的未来我决定 提交于 2019-12-21 02:57:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!