我的问题与Rails 3 ActiveRecord: Order by count on association非常相似
给定相同的场景,其中模型
Song has many :listens
我想根据收听者的数量对歌曲进行分组。我的目标是看到歌曲的分布与收听数量的对比。就像..。
song_listen_distribution = {0 => 24, 1 => 43, 2=>11, ... MAX_LISTENS => 1}这样song_listen_distribution[4]就会返回收听了4次的歌曲数量。
上面链接的问题的公认答案使我非常接近,但我无法按"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")发布于 2013-11-06 05:03:37
您要查找的内容不能很好地映射到标准ActiveRecord查询。
您可以直接调用SQL来最有效地获得您正在寻找的内容:
subquery = Song.joins(:listens).group(:id).select("songs.id, COUNT(*) as listen_count).to_sql
raw = Song.connection.select_rows("SELECT listen_count, COUNT(*) FROM (#{subquery}) t GROUP BY listen_count ORDER BY listen_count DESC")
song_listen_distribution = Hash[raw]或者,您可以使用ActiveRecord查找所有歌曲的计数,然后在ruby中构建分发字典:
song_listens = Song.joins(:listens).group(:id).count
song_listen_distribution = song_listens.group_by{|n| n.last}.
each_with_object({}){|(k, g), h| h[k] = g.size}https://stackoverflow.com/questions/19798105
复制相似问题