Ruby on rails Rails高级活动记录查询

Ruby on rails Rails高级活动记录查询,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我想通过连接对我的模型进行高级活动记录查询,并统计所有记录。我不知道是否有可能做到我想做的,但我认为这是可以做到的 我想知道一首歌在电台播放了多少次。我尝试了以下方法,但显然无效 @top_songs = Song.joins(:radiostation).where("radiostations.id = ?", 1).order(total_counter: :desc) 虽然使用了Generalplaylist模型,但我也使用了group,但缺点是它会产生一个哈希,而不是ActiveRe

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

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

@top_songs = Song.joins(:radiostation).where("radiostations.id = ?", 1).order(total_counter: :desc)
虽然使用了Generalplaylist模型,但我也使用了group,但缺点是它会产生一个哈希,而不是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
generalplaylist.rb
类Generalplaylist
在分组和计数后,ActiveRecord关系实际上并不适用

group和count将为您提供聚合结果,而ActiveRecord关系实际上是为您需要对单个记录进行行级访问而设计的


因此,在本例中,哈希就是您想要的结果。

如果您想要一个ActiveRecord关系(尽管Joshua指出您实际上并不需要),您可以使用Generalplaylist。假设您想在特定电台对特定歌曲进行计数,您可以

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

嗨,Joshua,我最终使用了分组方法,并对分组进行处理,以找到我要查找的歌曲细节。这对我的处境似乎是最好的。谢谢你的帮助!谢谢史蒂夫的支持。我最终使用了小组方法,因为这一定适合我的情况。没问题,很高兴你找到了解决方案!