与this问题非常相似,但不完全相同。
我有音乐家和乐器模型:
# musician.rb
class Musician < ActiveRecord::Base
attr_accessible :instrument_attributes
has_many :instrument_choices
has_many :instruments, through: instrument_choices
accepts_nested_attributes_for :instruments # with some other stuff
end
# instrument.rb
class Instrument < ActiveRecord::Base
has_many :inverse_instrument_choices, class_name: "InstrumentChoice"
has_many :musicians, through: :inverse_instrument_choices
validates_uniqueness_of :name
# instrument_choice.rb
class InstrumentChoice < ActiveRecord::Base
belongs_to :musician
belongs_to :instrument
validates_uniqueness_of :musician_id, scope: :instrument_id
我有一个静态的可能乐器列表,用户可以在新视图和编辑视图中以选择的形式从该列表中进行选择。假设所有这些工具都有现有记录。如何处理在音乐家和乐器之间添加新的关联?
谢谢!
答案 0 :(得分:2)
您可以通过关联或直接创建记录来创建InstrumentChoice
:
musician.instrument_choices.create(instrument: an_instrument)
# or
InstrumentChoice.create(musician: a_musician, instrument: an_instrument)
由于您并未在InstrumentChoice
中存储任何其他信息,因此可以使用不需要自己模型的简单连接表:
class Musician < ActiveRecord::Base
has_and_belongs_to_many :instruments
end
class Instrument < ActiveRecord::Base
has_and_belongs_to_many :musicians
end
musician.instruments << an_instrument
为确保唯一性,您可以为连接表添加唯一约束。