Ruby On Rails 4、在嵌套关联内动态创建嵌套关联

Ruby On Rails 4, dynamically create nested association inside a nested association

我有3个模型

class Patient < ActiveRecord::Base
  has_one :address, as: :person
  has_many :doctors
  accepts_nested_attributes_for :address, :reject_if => :all_blank, :allow_destroy => true
  validates_associated :address
  accepts_nested_attributes_for :doctors, :reject_if => :all_blank, :allow_destroy => true
  validates_associated :doctors
end

class Doctor < ActiveRecord::Base
  after_initialize :init, unless: :persisted?
  has_one :address, as: :person
  belongs_to :patient
  accepts_nested_attributes_for :address, :reject_if => :all_blank, :allow_destroy => true
  validates_associated :address

  def init
    self.address ||= build_address
  end
end

class Address < ActiveRecord::Base
  belongs_to :person, polymorphic: true
end

我正在使用 simple_form 和 cacoon 来处理我的 UI。 我不得不要求专家在模型级别初始化地址,否则专家的地址不会为 cacoon 初始化。

在我的控制器中,我使用

启动我的医生和地址
@patient.doctor.build
@patient.address ||= Address.new

但是,如果专家地址的每个输入都是空白,我会收到一条错误消息。

SQLite3::ConstraintException: NOT NULL constraint failed: addresses.line_1: INSERT INTO "addresses" ("person_type", "person_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)

这是否意味着它会在保存期间自动生成地址,即使

accepts_nested_attributes_for :address, :reject_if => :all_blank, :allow_destroy => true

设置了吗?

有什么办法可以解决吗?还是有更好的方法来实现我想要的?

您不应该使用 init 方法来初始化地址。相反,您应该使用 cocoon 提供的 :wrap_object 选项 (documentation).

例如,在你的情况下会变成这样

link_to_add_association 'add doctor', f, :doctors, wrap_object: Proc.new {|doctor| doctor.build_address; doctor }