如何获得最高计数的关联模型(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列。
- Rails 4:Model:Class的未定义方法`relation_delegate_class’
- Rails“ActiveRecord_Associations_CollectionProxy的未定义方法”
- 在Rails中创建大规模HABTM关联的最快方法是什么?
- ActiveRecord after_initialize with select
- 如何获取ActiveRecordvalidation中配置的最大长度?
- rails scope和join
- ActiveRecord,通过多态属性查找
- Rails ActiveRecord:是否可以组合:include和:conditions查询?
- Active Record不存在连接表记录的情况