订购产品通过关联数 [英] Order products by association count
问题描述
Class Product
has_many :sales
end
Class Sale
belongs_to :product
end
我如何获得最畅销的产品。(产品经..塔斯发现所有..为了..)?
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...
编辑:忽略我的答案的其余部分。它不会返回的产品对象由销售价值降序排列,它会返回与该产品相关的销售对象由销售价值降序排列。 :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屋!