2013-05-14 122 views
0

用的has_many保存模型,我爲有模型,如軌如何通過關聯

// Contains the details of Parties (Users) 
class Party < ActiveRecord::Base 
has_many :party_races 
has_many :races, :through=>:party_races 
end 

// Contains the party_id and race_id mappings 
class PartyRace < ActiveRecord::Base 
belongs_to :party 
belongs_to :race 
end 

// Contains list of races like Asian,American,etc.. 
class Race < ActiveRecord::Base 
has_many :party_races 
has_many :parties, :through => :party_races 
end 

現在,讓我們說我創建黨 party_instance = Party.new

的實例,我怎麼加多個種族party_instance並保存到數據庫?

回答

0

您也可以爲每個種族的新PartyRace,您可以添加:

def addRace(party_instance, new_race) 
    party_race = PartyRace.new(party: party_instance, race: new_race) 
    party_race.save 
end