I am writing an app where each User has many posts. I would like to generate a top 3 list of the users with the most posts. The only way I can think of is to get all the posts and count how many each user has. This seems extremely expensive, and not scalable. Accuracy is important. Does anyone have any suggestions?
Share
Post.group(:user_id).order("count_all DESC").limit(3).countshould do the job. It groups the posts by the user, orders them after the number of posts and returns just the 3 with the most posts. the sql query may be more easy to understand:
(0.3ms) SELECT COUNT(*) AS count_all, user_id AS user_id FROM "posts" GROUP BY user_id ORDER BY count_all DESC LIMIT 3and rails returns for you a hash like this:
{user_id => number_of_posts, user_id => number_of_posts, user_id => number_of_posts}