次のモデルを検討します。
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
存在する可能性はありますか?Father
ObjectSpace
Child