【发布时间】: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