posixpascal
posixpascal

Reputation: 3140

Rails ActiveRecord - Select user with most comments

I wanted to select the User with the highest comments.

The comments are in a relation.

I can query them through:

User.first.comments

Now I wanted to select the User with the most comments.

I do not want to loop through the whole User-Table, because this is very time consuming.

Maybe something like this:

User.joins(:comments).find(:all, :order => "COUNT(comments) desc")

But this does not work.

If no solution is possible, I will cache them in an external table.

Upvotes: 1

Views: 982

Answers (1)

Maurício Linhares
Maurício Linhares

Reputation: 40333

You should use a counter cache for that, here's an example:

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
end

Then you must add a comments_count column to the users table and whenever a new comment is created with a user this field is incremented automatically. In the end, your query could be like this:

User.order( "comments_count desc" ).limit(10).all

Upvotes: 8

Related Questions