简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM