3

I have a comment model which has likes associated with it. I keep the likes in a separate table and the comment model has_many likes. However, I want to order the comments by most popular and I do not know how to do an active directory query to return the order I want. I have tried:

Comment.order(:likes.count)

This isn't working. Any advice?

user265193
  • 31
  • 3
  • possible duplicate of [Rails 3 ActiveRecord: order by count on association](http://stackoverflow.com/questions/8696005/rails-3-activerecord-order-by-count-on-association) – infused Feb 26 '15 at 04:39

2 Answers2

1

This is working for me currently with Rails 5:

Comment.joins(:likes)
  .select('comments.*, count(likes) as like_count')
  .group('comments.id')
  .order('like_count desc')

It even adds a like_count attribute to each returned comment, so you can call comment.like_count.

chadoh
  • 4,343
  • 6
  • 39
  • 64
0

Try this:

Comment.joins(:likes).order('count(likes.*) desc')
PJ Bergeron
  • 2,788
  • 4
  • 25
  • 42
Mingsheng
  • 1,031
  • 10
  • 16