我正在构建一个音乐管理 Rails 应用程序,我的应用程序的用户将能够制作专辑的有序播放列表,并且每张专辑都有一个有序的歌曲列表。
本质上,这看起来像:
class User < ActiveRecord::Base
has_many :playlists, :order => "position"
has_many :albums, :through => :playlists
end
class Playlist < ActiveRecord::Base
belongs_to :user
belongs_to :album
end
class Album < ActiveRecord::Base
has_many :songs, :order => "position"
has_many :playlists
end
class Song < ActiveRecord::Base
belongs_to :album
end
(我习惯使用歌曲和播放列表表中acts_as_list
的position
列来分别管理歌曲和播放列表的排序顺序。)
现在我想找到给定用户的所有歌曲列表(按顺序)。如果我将此范围添加到Song模型中:
scope :for_user, lambda{|user|
joins(:album => {:playlists => :user}).
where(:'users.id' => user.id)
}
我可以这样做,但是返回的记录没有按顺序保存。相反,我希望看到每首歌曲首先按其专辑的用户播放列表位置排序,然后按歌曲在该专辑中的位置排序。换句话说,如果用户想按顺序播放专辑 A、B 和 C,我正在寻找 A 中所有歌曲的数组(按专辑中的顺序),以及 B 中的所有歌曲(按顺序),加上 C 中的所有歌曲(按顺序)。
我已经在范围内尝试了几种顺序和组子句的排列,但没有一个具有在排序专辑的上下文中排序歌曲的预期效果。