Reputation: 636
very similar to this question, but not quite the same.
I have Musician and Instrument models:
# 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
I have a static list of possible instruments, and the user selects from that list in a select form in the new and edit views. Assume all these instruments have existing records. How do I handle adding new associations between musician and instrument?
Thanks!
Upvotes: 1
Views: 1051
Reputation: 10054
You can create the InstrumentChoice
either through an association or by creating the record directly:
musician.instrument_choices.create(instrument: an_instrument)
# or
InstrumentChoice.create(musician: a_musician, instrument: an_instrument)
Since you're not really storing any additional information in InstrumentChoice
you could use a simple join-table that does not require its own model:
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
To ensure the uniqueness you can add a unique constraint to the join table.
Upvotes: 2