基本Rails 3问题:如何对产品进行排序?

我有以下型号:

Product: name, shop_id (foreign key), brand_id (foreign key), price Shop: name Brand: name 

协会是:

 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 

ProductsController#list我想获得按商店名称排序的所有产品的列表,然后按品牌名称排序。

我试着做:

 @products = Product.order("products.shop.name ASC, products.brand.name ASC") 

但它不起作用(我猜因为products.shop.name在数据库级别不存在)。

这样做的正确方法是什么?

奥斯汀L是对的,但他的语法有点陈旧。 新的ActiveRecord语法更清晰:

 @products = Product.includes(:shop, :brand).order("shops.name ASC, brands.name ASC") 

请参阅此文章: http : //www.definenull.com/node/8

在你的例子中:

 @products = Product.find(:all,:include => [:shop, :brand], :order => 'shops.name ASC, brands.name ASC') 

我自己没有测试过这个代码所以我不能100%保证它,但试一试。 如果它起作用,请尝试移除“ASC”并查看是否运行。

Interesting Posts