Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 916
amaseuk Avatar asked Mar 16 '12 14:03

amaseuk


1 Answers

User
  .joins(:solutions)
  .select("users.*, count(solutions.id) as scount")
  .group("users.id")
  .order("scount DESC")
like image 100
gayavat Avatar answered Sep 28 '22 01:09

gayavat