【问题标题】:Rails 3 ActiveRecord: order and group by association countRails 3 ActiveRecord:按关联计数排序和分组
【发布时间】: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 of Songs`。我还要稍微编辑一下我的问题。我正在删除范围部分,因为我只对查询感兴趣。
  • 之所以提到“pry”是因为我不熟悉它,而且我知道它会稍微操纵 Rails 控制台响应。

标签: sql ruby-on-rails-3 activerecord count associations


【解决方案1】:

您要查找的内容不能很好地映射到标准 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}

【讨论】:

  • ...我什至不知道该说什么。但那 8sht 看起来令人印象深刻。我什至不知道我在寻找什么,我现在真的在研究 AngularJs 的东西,但我相信我正在寻找对 AR 记录进行分组的帮助。无论如何,我什至不能把它们放在一起,但是这两个查询——子查询加上你使用 each_with_object 的第二个查询,它们看起来都很棒。我现在太累了,无法弄清楚,但这是非常繁重的工作,这可能很有用。不仅仅是因为 SQL,还因为它与 Rails ActiveRecord 的集成方式。加上一个儿子
  • @PinnyM 你能帮帮我吗,我也有类似的问题...stackoverflow.com/questions/23850832/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多