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

StackOverflow https://stackoverflow.com/questions/10170722

Pregunta

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?

¿Fue útil?

Solución

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

Event.order("events.users_count DESC")
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top