Is it a good idea to use ObjectSpace to find parent ActiveRecord in a validation chain?

75 views Asked by At

Considering following models:

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

Goal is to make sure Child cannot be created without a parent, i.e. Father. Now if father tries to create Child in a nested form, by the time the validation Child is being validated Father has not received an ID yet, thus the validation will fail. One proposed solution is to use ObjectSpace as the following:

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

Is it a good Idea to use ObjectSpace (e.g. Father) in the validation chain? Can there exist another Father in ObjectSpace which by chance is being created at the same time and has a child with the exact same attributes as the Child in question?

0

There are 0 answers