Search code examples
ruby-on-railsmodels

Order parent model using children in rails


I have model product and vote, I need to order products by votes count DESC.

product has_many :votes, vote belongs_to :product

index_controller.rb

def index
  @products = Product.all
end

Solution

  • @products = Product.order("count(votes) DESC")
    

    If you have not votes column then use:

    @products = Product.all.sort { |a, b| b.votes.count <=> a.votes.count   }