2

次のモデルを検討します。

class Father < ActiveRecord::Base
  has_many :children, as: :parent, dependent: :destroy
  accepts_nested_attributes_for :child
end

class Child < ActiveRecord::Base
  belongs_to :parent, polymorphic: true
  validates :parent_id, presence: true
end

目標はChild、親なしでは作成できないことを確認することFatherです。父親Childがネストされたフォームで作成しようとすると、検証Childが検証さFatherれるまでにIDをまだ受け取っていないため、検証は失敗します。提案された解決策の1 つはObjectSpace、次のように使用することです。

class Address < ActiveRecord::Base
  belongs_to :parent, polymorphic: true

  validates_presence_of :parent
  validates_presence_of :parent_id, :unless => Proc.new { |p|
    if (new_record? && !parent && parent_type)
      parent = nil
      ObjectSpace.each_object(parent_type.constantize) do |o|
        parent = o if o.children.include?(p) unless parent
      end
    end
    parent
  }
end

検証チェーンでObjectSpace(たとえば)を使用するのは良い考えですか? たまたま同時に作成されていて、その子とまったく同じ属性の子がFather存在する可能性はありますか?FatherObjectSpaceChild

4

0 に答える 0