2010-11-04 62 views
2

保存在Rails的額外的字段我在我的Rails應用程序的結構如下:如何使用has_and_belongs_to_many

class Movie < ActiveRecord::Base 
    has_and_belongs_to_many :celebs, :join_table => "movies_celebs" 
end 
class Celeb < ActiveRecord::Base 
    has_and_belongs_to_many :movies, :join_table => "movies_celebs" 
end 
class MovieCeleb < ActiveRecord::Base 
    belong_to :movie 
    belong_to :celeb 
end 

現在MovieCeleb有2個額外的字段CastName(串),CastType('演員/導演)。當我保存電影時,我也創建了明星,並將名人填入名人關係,並將movies_celebs自動保存到數據庫中。但我怎麼能通過CastName和CastType來保存。

請告知

在此先感謝。

回答

3

請注意以下幾點是爲Rails V2

script/generate model Movie id:primary_key name:string 
    script/generate model Actor id:primary_key movie_id:integer celeb_id:integer cast_name:string cast_type:string 
    script/generate model Celeb id:primary_key name:string 

model/movie.rb 
    class Movie < ActiveRecord::Base 
     has_many :actors 
     has_many :celebs, :through => :actors 
    end 

model/celeb.rb 
    class Celeb < ActiveRecord::Base 
     has_many :actors 
     has_many :movies, :through => :actors 
    end 

model/actor.rb 
    class Actor < ActiveRecord::Base 
     belongs_to :movie 
     belongs_to :celeb 
    end 

測試與紅寶石的關聯應用程序文件夾軌控制檯

>script/console 
>m = Movie.new 
>m.name = "Do Androids Dream Of Electric Sheep" 
>m.methods.sort #this will list the available methods 

#Look for the methods 'actors' and 'celebs' - these     
#are the accessor methods built from the provided models 

>m.actors   #lists the actors - this will be empty atm 
>c = Celeb.new 
>c.name = "Harrison Ford" 
>m.celebs.push(c) #push Harrison Ford into the celebs for Blade Runner 
>m.actors   #Will be empty atm because the movie hasnt been saved yet 
>m.save   #should now save the Movie, Actor and Celeb rows to relevant tables 
>m.actors   #Will now contain the association for 

#Movie(id : 1, name : "Do Androids..") - Actor(id : 1, movie_id : 1, celeb_id : 1) - 
#Celeb(id : 1, name : "Harrision Ford") 

>m = Movie.new  #make a new movie 
>m.name = "Star Wars" 
>m.celebs.push(c) #associated the existing celeb with it 
>m.save 
>movies = Movie.all #should have the two movies saved now 
>actors = Actor.all #should have 2 associations 
>this_actor = Actor.first 
>this_actor.cast_type = "ACTOR" 
>this_actor.save 

然後你'可能會想看看瑞安貝茨的電視廣播http://railscasts.com#47(兩個多對多)和#73,#74,#75(複雜形式部分1-3)。

網頁上有多個表格代碼的更新版本,用於#75。

4

如果您需要連接模型上的驗證,回調或額外屬性,則應該使用has_many:through而不是has_and_belongs_to_many。

參見:

http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

+0

我正在學習軌道上的紅寶石。你能給出一個示例代碼什麼是使用has_many:through保存數據的最佳方法。 – 2010-11-04 09:35:47

+0

點擊鏈接並查看示例。如果你使用has_many:through而不是h_a_b_t_m,你會得到兩個關係而不是一個關係,即與movie_celeb的關係以及與電影/名人的關係。因此,您將能夠在movie_celeb關係模型中讀取/寫入屬性。 – 2010-11-04 09:52:11

相關問題