本文介绍了基本 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
中,我想获取按商店名称和品牌名称排序的所有产品的列表.
In ProductsController#list
I would like to get a list of all products sorted by shop name and then by brand name.
我尝试这样做:
@products = Product.order("products.shop.name ASC, products.brand.name ASC")
但它不起作用(我猜是因为products.shop.name
在数据库级别不存在).
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 是对的,但他的语法有点旧.新的 ActiveRecord 语法更加简洁:
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")
这篇关于基本 Rails 3 问题:如何对产品进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!