My question is very similar to Rails 3 ActiveRecord: Order by count on association
Given the same scenario where the model
Song has many :listens
I would like to group the songs by the number of listens. My goal is to see a distribution of songs vs listen count. Something like...
song_listen_distribution = {0 => 24, 1 => 43, 2=>11, ... MAX_LISTENS => 1}
so that song_listen_distribution[4]
would return the number of songs listened to 4 times.
The accepted answer to the linked question above gets me very close, but I am unable to group by "songs.listens_count"
Song.select("songs.id, OTHER_ATTRS_YOU_NEED, count(listens.id) AS listens_count").
joins(:listens).
group("songs.listens_count").
order("listens_count DESC")