![](/img/trans.png)
[英]How to get attributes of model in has_many :through association in Rails 5
[英]rails how to save a model with has_many through association
我有像這樣的模特
// 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 party_instance = Party.new
的實例
我應該如何將多個Race添加到party_instance
並保存到數據庫?
您還可以為每個種族添加新的PartyRace:
def addRace( party_instance, new_race )
party_race = PartyRace.new( party: party_instance, race: new_race )
party_race.save
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.