How to get highest count of associated model (Rails)?
Asked Answered
G

3

10

A User has_many Solutions

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?

Gaudy answered 16/3, 2012 at 14:49 Comment(0)
B
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

Brythonic answered 16/3, 2012 at 15:6 Comment(0)
S
26
User
  .joins(:solutions)
  .select("users.*, count(solutions.id) as scount")
  .group("users.id")
  .order("scount DESC")
Sapodilla answered 16/3, 2012 at 14:59 Comment(0)
B
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

Brythonic answered 16/3, 2012 at 15:6 Comment(0)
N
5

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

The query will then be

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

Don't forget to index the solutions_count column.

Nickelsen answered 16/3, 2012 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.