我想选择评价最高的用户。
评论是有关系的。
我可以通过以下方式查询:
User.first.comments
现在我想选择评论最多的用户。
我不想遍历整个用户表,因为这非常耗时。
也许是这样的:
User.joins(:comments).find(:all, :order => "COUNT(comments) desc")
但这不起作用。
如果无法解决,我会将它们缓存在外部表中。
答案 0 :(得分:8)
你应该使用一个计数器缓存,这是一个例子:
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user, :counter_cache => true
end
然后,您必须在用户表中添加 comments_count 列,并且每当为用户创建新评论时,此字段会自动递增。最后,您的查询可能是这样的:
User.order( "comments_count desc" ).limit(10).all