【问题标题】:How to get highest count of associated model (Rails)?如何获得最高数量的关联模型(Rails)?
【发布时间】:2012-03-16 14:49:01
【问题描述】:

一个用户有_many解决方案

如何按解决方案最多的用户排序用户?

我正在尝试查找前十名的用户,但我不确定如何做到这一点最整洁或最有效?

有没有人有一个计算成本不是太高的例子?

【问题讨论】:

    标签: ruby-on-rails activerecord has-many


    【解决方案1】:
    User
      .joins(:solutions)
      .select("users.*, count(solutions.id) as scount")
      .group("users.id")
      .order("scount DESC")
    

    【讨论】:

      【解决方案2】:

      如果您真的想要一种快速的方法,请将counter_cache 放在用户的解决方案上(在您的User 中有一个solutions_count 列)并按该列排序。您不需要管理该计数器,因为 rails 会为您完成。您可以在Rails Guides 中阅读有关counter_cache 的更多信息

      【讨论】:

        【解决方案3】:

        假设以下模型

        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 列建立索引。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多