I have a model named Song
. I also have a model named Listen
. A Listen
belongs_to :song
, and a song :has_many listens
(can be listen to many times).
In my model I want to define a method self.top
which should return the top 5 songs listened to the most. How can I achieve that using the has_many
relation?
I'm using Rails 3.1.
Thanks!
For rails 4.x try this if your rows without any association matters:
Using named scopes:
Even better, use
counter_cache
which will be faster because you'll only because using one table in your queryHere is your song class:
Then, your listen class:
Make sure you add a migration:
Bonus points, add test:
Or, if you want to go with the above method, here it is a bit more simply, and using a class method rather than
scope