Validates presence of each other in two associated models

Posted by Sergey Alekseev on Stack Overflow See other posts from Stack Overflow or by Sergey Alekseev
Published on 2012-04-05T22:27:32Z Indexed on 2012/04/05 23:28 UTC
Read the original article Hit count: 192

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby