我试图将每个播放列表的第一首歌曲加入播放列表阵列,并且在寻找有效解决方案时遇到了相当困难的时间。从一个有很多通过协会获得第一个协会
我有以下型号:
class Playlist < ActiveRecord::Base
belongs_to :user
has_many :playlist_songs
has_many :songs, :through => :playlist_songs
end
class PlaylistSong < ActiveRecord::Base
belongs_to :playlist
belongs_to :song
end
class Song < ActiveRecord::Base
has_many :playlist_songs
has_many :playlists, :through => :playlist_songs
end
我希望得到这样的:
playlist_name | song_name
----------------------------
chill | baby
fun | bffs
我有一个非常艰难的时间找到一个有效的方法通过加入做到这一点。
UPDATE * ***
巴蒂尔安德拉德已经导致我在正确的方向,但我还是不能让正是我想要的。
这是据我已经能够得到:
playlists = Playlist.where('id in (1,2,3)')
playlists.joins(:playlist_songs)
.group('playlists.id')
.select('MIN(songs.id) as song_id, playlists.name as playlist_name')
这给了我:
playlist_name | song_id
---------------------------
chill | 1
这是接近,但我需要的第一首歌曲(根据ID)的名字。
想要加入每首歌曲的播放列表是什么?包含这首歌曲的所有播放列表? – Leito 2013-03-08 19:46:43
您是否尝试搜索具有给定名称和给定歌曲的所有播放列表,或者是否只想输出第一首歌曲旁边所有playlist_name的数组? – 2013-03-08 19:50:44
@rocketscientist后来。他们的第一首歌曲旁边的playlist_names – mrabin 2013-03-08 20:08:39