2012-02-08 41 views
0

假設我們在rails中有專輯,藝術家和歌曲模型。Rails多對多的關係和遠程關係

在專輯:

class Album < ActiveRecord::Base 
    has_many :artist_album 
    has_many :artist, :through => :artist_album 
    has_many :song 

在artistalbum:

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 

回答

0

你錯過了ArtistSong模式?通常我們在has_many中使用複數形式,即has_many :artist_songs

如果你有ArtistAlbum加盟模式,你不需要去Song部分...如果你有以下設置只是artist.albums

class Artist < ActiveRecord::Base 
    has_many :artist_albums 
    has_many :albums, :through => :artist_albums 
end 

以下是你可以使用的,但不一定需要。

class ArtistAlbum < ActiveRecord::Base 
    belongs_to :artist 
    belongs_to :album 
end 

class Album < ActiveRecord::Base 
    has_many :artist_albums 
    has_many :artist, :through => :artist_albums 
end 
+0

謝謝,這讓我開始了一個基本的模型! – Bill 2012-02-14 16:25:54