Search code examples
ruby-on-railsruby-on-rails-3.1rails-3.1

rails 3.1 How to retrieve in a query those elements with the maximum number of relationships in a many to many?


I have tried different combinations but it seems that I cannot work this out.

I want to retrieve, from an Event model, those events which have the biggest number of users.

For example, I retrieve users of an event like this

@users = Event.find(x).users

They can be counted using this

Event.find(x).users.count

So, How should be done to order the list by the number of users each event has. And then retrieve the 8 first?


Solution

  • The same issue was resolved in: How to get highest count of associated model (Rails)?

    Event.order("events.users_count DESC")