【问题标题】:has_many :through with existing objecthas_many :通过现有对象
【发布时间】:2023-03-15 22:27:02
【问题描述】:

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

我有一个可能的工具的静态列表,用户在新视图和编辑视图中的选择表单中从该列表中进行选择。假设所有这些工具都有现有记录。如何在音乐家和乐器之间添加新的关联?

谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord associations has-many-through


    【解决方案1】:

    您可以通过关联或直接创建记录来创建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
    

    为确保唯一性,您可以向连接表添加唯一约束。

    【讨论】:

    • 感谢您的快速回复,菲利普。问题是我在create 操作中执行@musician = Musician.new(params['musicians']),所以我认为它会尝试自动为我创建关联,这不是我想要的,因为它会尝试创建新的乐器记录。我应该只是一块一块地加载参数,然后按照你说的建立关联吗?
    • 所以当你想存放乐器时,音乐家是不存在的?另外,我看到params['musicians'],你是不是想同时创建多个音乐家?
    • 对不起,我指的是音乐家。我需要考虑这两种情况:创建音乐家配置文件并添加其乐器,以及编辑我可能(或可能不会)添加/删除乐器关联的音乐家配置文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多