按关联计数订购产品 [英] Order products by association count
问题描述
类产品
has_many :sales
end
Class Sale
belongs_to :product
end
我如何获得最畅销的产品..(产品查找所有.. 由.. ventas 订购..)?
How do i get the most sold products.. (Product find all.. order by .. ventas..) ?
推荐答案
在检索产品时,您可以:
When retrieving the Products, you could do:
@products = Product.find(:all, :include => :sales, :order => "sales.value DESC")
'sales.value' 可以替换为您尝试订购的任何值...
'sales.value' can be replaced with whatever value you are trying to order by...
忽略我的其余答案.它不会按销售额降序返回 Product 对象,而是按销售额降序返回与 Product 关联的 Sales 对象.:P
Disregard the rest of my answer. it won't return the Product objects in descending order by sale value, it'll return the Sales objects associated with the Product in descending order by sale value. :P
此外,您可以在模型中指定排序,例如:
Also, you can specify the ordering in your model like:
Class Product
has_many :sales, :order => 'sale_value DESC'
end
'sale_value' 是您想要订购的任何东西......并且这样做,要检索产品,您可以这样做:
where the 'sale_value' is whatever you're trying to order by... and doing it this way, to retrieve the Products, you can just do:
@products = Product.all
这篇关于按关联计数订购产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!