如何获得最高计数的关联模型(Rails)?

用户has_many解决方案

如何为拥有最多解决方案的用户订购用户?

我正在努力寻找十大用户,但我不确定如何做到最干净或最有效的方法呢?

有没有人有一个计算成本太高的例子?

如果您真的想要一种快速的方法,请在用户的解决方案上放置一个counter_cache在用户中有一个solutions_count列)并按该列排序。 您不需要管理该计数器,因为rails会为您执行此操作。 您可以在Rails指南中阅读有关counter_cache更多信息

 User .joins(:solutions) .select("users.*, count(solutions.id) as scount") .group("users.id") .order("scount DESC") 

假设有以下型号

 class User has_many :solutions end class Solution belongs_to :user end 

然后最好的方法是counter_cache solutions_count并按顺序排序。 更多关于counter_cache

然后查询将是

 User.order("users.solutions_count DESC").limit(10) 

不要忘记索引solutions_count列。