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?
UPDATE:
The code below works well in my environment ( Rails3.2.2, ruby 1.8.7)
run this test and got:
PREVIOUS ANSWER ================
try to initialize them separately, then add the association, at last save them.
for more details of “build, create”, see its official website: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md