1

我有以下两个模型:

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 对象才能通过存在验证。看起来我在这里有某种无限递归。

如何解决?

4

1 回答 1

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

于 2012-04-05T22:30:38.493 回答