Order products by association count

后端 未结 3 1609
再見小時候
再見小時候 2020-12-09 07:10

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 07:32

    When retrieving the Products, you could do:

     @products = Product.find(:all, :include => :sales, :order => "sales.value DESC")
    

    'sales.value' can be replaced with whatever value you are trying to order by...


    EDIT: 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
    

    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
    

提交回复
热议问题