【发布时间】:2013-11-05 20:17:21
【问题描述】:
我的问题与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")
【问题讨论】:
-
当您说您“无法按
songs.listens_count分组”时,您是什么意思?有错误还是没有按您的意愿显示? -
我在工作中这样做,他们使用我有点不熟悉的 pry。当我运行上述查询时,我看到
#<ActiveRecord::Relation:0x35e894c>作为响应。如果我把它切换到group("songs.id") then I'm returned an array ofSongs`。我还要稍微编辑一下我的问题。我正在删除范围部分,因为我只对查询感兴趣。 -
之所以提到“pry”是因为我不熟悉它,而且我知道它会稍微操纵 Rails 控制台响应。
标签: sql ruby-on-rails-3 activerecord count associations