我有以下两种模式:
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
我想创建父对象。
如果我执行以下操作:
Parent.create!
或Factory(:parent)
异常引发:ActiveRecord::RecordInvalid: Validation failed: Child can't be blank
但是由于同样的原因,我无法在没有Parent对象的情况下创建Child对象 - 我需要先创建Parent对象才能通过在线验证。
看来我在这里有一些无限递归。
怎么解决?
答案 0 :(得分:2)
更新:
以下代码在我的环境中运行良好(Rails3.2.2,ruby 1.8.7)
# parent.rb
class Parent < ActiveRecord::Base
has_one :child
validates :child, :presence => true
end
# child.rb
class Child < ActiveRecord::Base
belongs_to :parent
validate :parent, :presence => true
end
# parent_test.rb
require 'test_helper'
class ParentTest < ActiveSupport::TestCase
test "should be saved" do
parent = Parent.new(:name => "111")
child = Child.new(:name => "222", :parent => parent)
parent.child = child
parent.save!
puts "after saved, parent: #{parent.inspect}"
puts "after saved, child: #{child.inspect}"
assert parent.id > 0
assert child.id > 0
end
end
运行此测试并得到:
Started
after saved, parent: #<Parent id: 980190963, name: "111", created_at: "2012-04-05 23:19:31", updated_at: "2012-04-05 23:19:31">
after saved, child: #<Child id: 980190963, name: "222", parent_id: 980190963, created_at: "2012-04-05 23:19:31", updated_at: "2012-04-05 23:19:31">
.
Finished in 0.172716 seconds.
1 tests, 2 assertions, 0 failures, 0 errors
以前的答案================
尝试单独初始化它们,然后添加关联,最后保存它们。
parent = FactoryGirl.build(:parent)
child = FactoryGirl.build(:child, :parent => parent)
parent.child = child
parent.save
child.save # seems this line of code is redundant? I am not sure.
有关“构建,创建”的更多详细信息,请参阅其官方网站:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md