ruby-on-rails - 在 rails 中选择元素的子集及其子元素

标签 ruby-on-rails ruby activerecord associations rails-postgresql

我有一组专辑,每张专辑都有歌曲。

我想过滤播放次数最多的歌曲的所有专辑,并且这些专辑中仅包含播放次数最多的歌曲的引用。

有点像

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/

相关文章:

ruby-on-rails - 使用 Webpacker 和 Rails 导入 npm 包的图像

ruby-on-rails - 如何编写一个 rake 任务来捆绑安装然后 rake db :migrate then rake db:seed?

ruby-on-rails - 从ActiveAdmin删除仪表板页面

ruby - 在 Ruby 中引用传递的 block 中的调用对象

ruby-on-rails - 如何使 Active Record 连接返回唯一的对象?

php - 不同/连接两个表

ruby-on-rails - Rails 4 中连接表的默认范围

ruby - 庭院和 C 扩展

Ruby rake 任务线程优化

ruby - 未显示载波错误消息