【发布时间】:2012-02-08 00:37:05
【问题描述】:
假设我们在 rails 中有专辑、艺术家和歌曲模型。
专辑中:
class Album < ActiveRecord::Base
has_many :artist_album
has_many :artist, :through => :artist_album
has_many :song
在专辑中:
class ArtistAlbum < ActiveRecord::Base
belongs_to :album
belongs_to :artist
end
在歌曲中:
class Song < ActiveRecord::Base
has_many :artist_song
has_many :artists, :through => :artist_song
belongs_to :album
在艺术家中:
class Artist < ActiveRecord::Base
has_many :artist_song
has_many :song, :through => :artist_song
是否可以通过活动记录选择以下记录集:
- 查找属于该艺术家的专辑
由于艺人依附于歌曲,而专辑只是歌曲的集合,艺人与专辑之间并无直接关系。
除了为相关艺术家选择属于每个专辑的每首歌曲
本质上是这样的:
SELECT albums.`name`
FROM artists INNER JOIN artist_songs ON artists.id = artist_songs.artist_id
INNER JOIN songs ON songs.id = artist_songs.song_id
INNER JOIN albums ON songs.album_id = albums.id
【问题讨论】:
标签: ruby-on-rails activerecord