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

时间:2012-03-16 14:49:01

标签: ruby-on-rails activerecord has-many

用户has_many解决方案

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

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

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

3 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分:5)

如果您真的想要快速完成此操作,请在用户的解决方案上添加counter_cachesolutions_count中有User列)并按该列排序。您不需要管理该计数器,因为rails会为您执行此操作。您可以在Rails Guides

中详细了解counter_cache

答案 2 :(得分:4)

假设以下型号

class User
  has_many :solutions
end

class Solution
 belongs_to :user
end

然后最好的方法是counter_cache solutions_count并按顺序排序。 more on counter_cache

然后查询

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

不要忘记索引solutions_count列。