【问题标题】:Select subset of elements and their children in rails在rails中选择元素的子集及其子元素
【发布时间】:2013-11-14 13:27:27
【问题描述】:

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

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

有点像

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 个对象,我需要根据这个查询将它们变成专辑,包括他们的歌曲

我希望我解决了这个问题。

【问题讨论】:

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


    【解决方案1】:

    来自Rails Doc

    如果您使用指定的 :limit 选项急切加载关联,它将被忽略,并返回所有关联的对象。

    试试这个:

    Album 
      title 
      year
      has_many :songs
      has_many :most_played_songs, -> { order('played_count DESC').limit(10) }, :class_name => 'Song'
      belongs_to :artist 
    

    【讨论】:

    • 如果我理解正确的话,这让我可以访问每张专辑中播放次数最多的十首歌曲,对吗?
    • 好吧,我不是这个意思。我想要一个专辑子集,包括播放次数最多的歌曲子集(前十名)。例如,如果我有 10 首热门歌曲,这些歌曲来自 5 张专辑,我只想过滤这 5 张专辑,而这些专辑只包含前 10 名的歌曲。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多