我在工厂上调用create时遇到Null违规错误。
这是我的两个模型:
# Table name: test_masters
# id :integer not null, primary key
class TestMaster < ActiveRecord::Base
has_one :test_slave, dependent: :destroy
end
# Table name: test_slave
# id :integer not null, primary key
# test_master_id :integer not null
class TestSlave < ActiveRecord::Base
belongs_to :test_master, dependent: :destroy
end
和以下工厂:
FactoryGirl.define do
factory :test_master do
test_slave
end
end
FactoryGirl.define do
factory :test_slave do
end
end
当我在rails控制台中运行FactoryGirl.create(:test_master)时,出现以下错误:
PG::NotNullViolation: ERROR: null value in column "test_master_id" violates not-null constraint
ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "test_master_id" violates not-null constraint
我以为从test_master工厂调用test_slave工厂会自动提供test_master_id ...,但事实并非如此。
我的工厂出问题了吗?
您的test_slave
工厂应定义创建有效记录所需的属性。由于您TestSlave
需要一个TestMaster
,因此需要在test_slave
工厂中进行定义。
简而言之,您在工厂中指定的关联方向错误。尝试以下方法:
FactoryGirl.define do
factory :test_master do
end
end
FactoryGirl.define do
factory :test_slave do
test_master
end
end
然后,当您执行时FactoryGirl.create(:test_slave)
,可以指定其TestMaster
:
master = FactoryGirl.create(:test_master)
FactoryGirl.create(:test_slave, test_master: test_master)
如果不指定该属性,它将为您生成一个:
FactoryGirl.create(:test_slave) # Generates a new TestMaster and uses that.
希望有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句