【问题标题】:Rails advanced Active Record queryRails 高级 Active Record 查询
【发布时间】:2017-04-22 06:37:19
【问题描述】:

我想通过连接对我的模型进行高级 Active Record 查询并计算所有记录。我不知道是否可以做我想做的事,但我认为可以做到。

我想知道一首歌曲在电台播放了多少次。我尝试了以下方法,但显然没有用。

@top_songs = Song.joins(:radiostation).where("radiostations.id = ?", 1).order(total_counter: :desc)

我也玩过 Group 以及 Generalplaylist 模型,但缺点是它给出了一个哈希结果而不是 ActiveRecord 关系。

Generalplaylist.where("radiostation_id = ?", 1).group(:song_id).count

还有其他方法可以得到结果吗?

这是我的电台播放列表网站的模型

generalplaylist.rb

class Generalplaylist < ActiveRecord::Base
  belongs_to :song
  belongs_to :radiostation
  belongs_to :artist
end

song.rb

class Song < ActiveRecord::Base
  has_many :generalplaylists
  has_many :radiostations, through: :generalplaylists
  belongs_to :artist
end

radiostaion.rb

class Radiostation < ActiveRecord::Base
  has_many :generalplaylists
end

class Artist < ActiveRecord::Base
  has_many :generalplaylists
  has_many :songs
  has_many :radiostations, through: :generalplaylists
end

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    在分组和计数之后,ActiveRecord 关系并不真正适用。

    组和计数将为您提供汇总结果,而 ActiveRecord 关系实际上是为您需要对单个记录进行行级访问而设计的。

    所以在这种情况下,散列就是你想要的结果。

    【讨论】:

    • 嗨 Joshua,我最终使用了组方法并处理了组以找到我正在寻找的歌曲详细信息。这似乎最适合我的情况。感谢您的帮助!
    【解决方案2】:

    如果您想要一个 ActiveRecord 关系(尽管 Joshua 指出您并不真正需要),您可以使用 Generalplaylist。假设您想在特定广播电台 my_radiostation 计算特定歌曲 my_song,您可以这样做...

    Generalplaylist.where(song: my_song, radiostation: my_radiostation).count
    

    【讨论】:

    • 感谢史蒂夫的回答。我最终使用了小组方法,因为这必须适合我的情况。
    • 没问题,很高兴您找到了解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2013-06-27
    相关资源
    最近更新 更多