ama*_*euk 9 activerecord ruby-on-rails has-many
用户has_many解决方案
如何为拥有最多解决方案的用户订购用户?
我正在努力寻找十大用户,但我不确定如何做到最干净或最有效的方法呢?
有没有人有一个计算成本太高的例子?
gay*_*vat 22
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 thesolutions_count 并按它排序。更多关于 counter_cache
然后查询将是
User.order("users.solutions_count DESC").limit(10)
不要忘记索引solutions_count 列。
| 归档时间: | 
 | 
| 查看次数: | 4242 次 | 
| 最近记录: |