wul*_*ong 3 sql activerecord count associations ruby-on-rails-3
我的问题与Rails 3 ActiveRecord非常相似:按关联计数排序
给出模型相同的场景
Song has many :listens
我想根据听众的数量对歌曲进行分组.我的目标是看到歌曲与听力的分布.就像是...
song_listen_distribution = {0 => 24, 1 => 43, 2=>11, ... MAX_LISTENS => 1}
Run Code Online (Sandbox Code Playgroud)
这样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")
Run Code Online (Sandbox Code Playgroud)
你正在寻找什么并不能很好地映射到标准的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]
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用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}
Run Code Online (Sandbox Code Playgroud)