我有一组专辑,每张专辑都有歌曲。
我想过滤播放次数最多的歌曲的所有专辑,并且这些专辑中仅包含播放次数最多的歌曲的引用。
有点像
Album.includes(:songs).order("songs.played_count DESC").limit(10)
但这限制了专辑而不是歌曲。
我想要 10 首最常播放的歌曲和专辑。
如果我从另一边去,比如
Song.includes(:album).order("songs.played_count DESC").limit(10)
我得到了所有的歌曲,但我想收到专辑。对于这个例子,我将不得不浏览歌曲并创建一个专辑集合,并且为每个专辑只设置选定的歌曲。
有没有更好的实现方式?
我的模型
Artist
name
has_many :albums
Album
title
year
has_many :songs
belongs_to :artist
Song
title
played_count
new
belongs_to :album
更新
我期望的结果示例。
前 10 首歌曲
Bad Religion - The New America | I Love My Computer
Linkin Park - Living Things | Caste of Glass
Linkin Park - Living Things | Skin to Bone
Kiss - Monster | Freak
Within Tempt. - Q Music Session | Titanium
Sunrise Avanue - On The Way .. | Fairytale Gone Bad
Linkin Park - Living Things | Roads Untravelled
Within Tempt. - Q Music Session | Radioactive
预期结果
Album <Bad Religion - The New America>
Song <I Love My Computer>
Album <Linkin Park - Living Things>
Song <Castle of Glass>
Song <Skin to Bone>
Song <Roads Untravelled>
Album <Kiss - Monster>
Song <Freak>
Album <Within Tempt. - Q Music Session>
Song <Titanium>
Song <Radioactive>
Album <Sunrise Avanue - On The Way ..>
Song <Fairytable Gone Bad>
简单的查询看起来像
SELECT albums.*, songs.* FROM albums
LEFT JOIN songs
ON songs.album_id = albums.id
ORDER BY songs.most_played
LIMIT 10
此查询返回 10 个对象,我需要根据此查询将它们转换为专辑,包括它们的歌曲
我希望我解决了这个问题。
最佳答案
来自Rails Doc :
If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects.
相反,试试这个:
Album
title
year
has_many :songs
has_many :most_played_songs, -> { order('played_count DESC').limit(10) }, :class_name => 'Song'
belongs_to :artist
关于ruby-on-rails - 在 rails 中选择元素的子集及其子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978910/