如何获得最高计数的关联模型(Rails)?

时间:2022-07-12 13:12:42

A User has_many Solutions

用户has_many解决方案

How do I order Users by those with the most Solutions?

如何为拥有最多解决方案的用户订购用户?

I'm trying to find the top ten users but I'm not sure how the most tidy or efficient way to do this?

我正在努力找到十大用户,但我不确定如何做到最干净或最有效的方法呢?

Does anyone have an example that isn't too computationally expensive?

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

3 个解决方案

#1


5  

If you really want a fast way of doing it, put a counter_cache on a users' solutions (have a solutions_count column in your User) and order by that column. You don't need to manage that counter, because rails does it for you. You can read more about counter_cache in the Rails Guides

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

#2


19  

User
  .joins(:solutions)
  .select("users.*, count(solutions.id) as scount")
  .group("users.id")
  .order("scount DESC")

#3


4  

Assuming the following models

假设有以下型号

class User
  has_many :solutions
end

class Solution
 belongs_to :user
end

Then the best way is to counter_cache the solutions_count and order by it. more on counter_cache

然后最好的方法是counter_cache solutions_count并按顺序排序。更多关于counter_cache

The query will then be

然后查询将是

User.order("users.solutions_count DESC").limit(10)

Don't forget to index the solutions_count column.

不要忘记索引solutions_count列。

#1


5  

If you really want a fast way of doing it, put a counter_cache on a users' solutions (have a solutions_count column in your User) and order by that column. You don't need to manage that counter, because rails does it for you. You can read more about counter_cache in the Rails Guides

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

#2


19  

User
  .joins(:solutions)
  .select("users.*, count(solutions.id) as scount")
  .group("users.id")
  .order("scount DESC")

#3


4  

Assuming the following models

假设有以下型号

class User
  has_many :solutions
end

class Solution
 belongs_to :user
end

Then the best way is to counter_cache the solutions_count and order by it. more on counter_cache

然后最好的方法是counter_cache solutions_count并按顺序排序。更多关于counter_cache

The query will then be

然后查询将是

User.order("users.solutions_count DESC").limit(10)

Don't forget to index the solutions_count column.

不要忘记索引solutions_count列。