订购产品通过关联数产品

2023-09-09 21:59:55 作者:我想成王 你定灭亡

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