1

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
Puce
  • 1,003
  • 14
  • 28
  • 3
    possible duplicate of [Rails order by results count of has\_many association](http://stackoverflow.com/questions/16996618/rails-order-by-results-count-of-has-many-association) – Puce Jun 23 '15 at 12:26
  • I don't want extra column in DB –  Jun 23 '15 at 12:29
  • You may not want it, but you're going to be full-scanning the product table and joining to the foreign key for every row in the votes table without it. With an index on the counter cache column of the product table you'll get an index range scan on any decent relational database. – David Aldridge Jun 23 '15 at 12:42

1 Answers1

0
@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   }
Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36