Validates presence of each other in two associated models
- by Sergey Alekseev
I have the following two models:
class Parent < ActiveRecord::Base
has_one :child, dependent: :destroy
validates :child, presence: true
end
class Child < ActiveRecord::Base
belongs_to :parent
validates :parent, presence: true
end
I want to create Parent object.
If I do the following:
Parent.create! or Factory(:parent)
Exception raises: ActiveRecord::RecordInvalid: Validation failed: Child can't be blank
But I can't create Child object without Parent object for the same reason - I need to create Parent object first in order to pass presence validation.
As it appears I have some kind of infinite recursion here.
How to solve it?