给定一个拥有多个 <model_name> 的用户,找到具有最多 <model_name> 的用户的正确方法是什么? [英] Given a user that has_many <model_name>, what is the correct way to find the user with the most <model_name>?

查看:28
本文介绍了给定一个拥有多个 <model_name> 的用户,找到具有最多 <model_name> 的用户的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,其中每个用户都有很多帖子.我想生成帖子最多的用户的前 3 名列表.我能想到的唯一方法是获取所有帖子并计算每个用户有多少.这似乎非常昂贵,而且不可扩展.准确性很重要.有没有人有什么建议?

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?

推荐答案

Post.group(:user_id).order("count_all DESC").limit(3).count

应该完成这项工作.它按用户对帖子进行分组,按照帖子数量对它们进行排序,并仅返回帖子最多的 3 个.sql查询可能更容易理解:

should 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 3

并且 rails 会为您返回这样的哈希值:

and rails returns for you a hash like this:

{user_id =>number_of_posts, user_id =>number_of_posts, user_id =>number_of_posts}

这篇关于给定一个拥有多个 <model_name> 的用户,找到具有最多 <model_name> 的用户的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆