UPDATE:
次のコードは、私の環境ではうまく動作します(Rails3.2.2、ルビー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
あなたは工場のコードを投稿してくださいだろうか? –
'validates:parent、presence:true'は有効ではないので、あなたが使っているRailsのバージョンが不思議です。 'validates:parent、:presence => true'である必要があります。 –
上記の抽象概念があります。私は多くの余分な属性を持つ複雑なモデルを持っているので、実際の工場のコードを投稿する理由はありません。 –