【问题标题】:Rails ActiveRecord - Select user with most commentsRails ActiveRecord - 选择评论最多的用户
【发布时间】:2012-04-16 02:10:53
【问题描述】:

我想选择具有最高 cmets 的用户。

cmets 有关系。

我可以通过以下方式查询:

User.first.comments

现在我想选择拥有最多 cmets 的用户。

我不想遍历整个用户表,因为这非常耗时。

可能是这样的:

User.joins(:comments).find(:all, :order => "COUNT(comments) desc")

但这不起作用。

如果无法解决,我会将它们缓存在外部表中。

【问题讨论】:

    标签: mysql ruby-on-rails ruby sqlite activerecord


    【解决方案1】:

    您应该为此使用计数器缓存,这是一个示例:

    class User < ActiveRecord::Base
      has_many :comments
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :user, :counter_cache => true
    end
    

    然后您必须将 cmets_count 列添加到 users 表中,并且每当与用户一起创建新评论时,此字段都会自动递增。最后,您的查询可能是这样的:

    User.order( "comments_count desc" ).limit(10).all
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2013-06-04
      • 2011-12-14
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多