![](/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.