用户has_many解决方案
如何为拥有最多解决方案的用户订购用户?
我正在努力寻找前十名用户,但我不确定如何做到最干净或最有效的方式?
有没有人有一个计算成本太高的例子?
答案 0 :(得分:21)
User
.joins(:solutions)
.select("users.*, count(solutions.id) as scount")
.group("users.id")
.order("scount DESC")
答案 1 :(得分:5)
如果您真的想要快速完成此操作,请在用户的解决方案上添加counter_cache
(solutions_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列。