我有以下设置。汽车与贷款挂钩,贷款需要分配给汽车。业务逻辑规定如果没有贷款,汽车就不存在。所以我将外键设置为null: false
。
现在我很难直接设置测试环境。
问题是after create
回调。我想在每次创建汽车后创建自动创建贷款。但是我暂时把汽车ID分配给了贷款。
我在下面使用的语法导致错误。每一个帮助表示赞赏
class Car < ActiveRecord::Base
has_one loan
end
class Loan < ActiveRecord::Base
belongs_to car
end
spec/factories.rb
factory :car
model Faker::GameOfThromes.house
manufactoring_plant Faker::StarWars.planet
after(:create) do |car|
create :loan, car_id: car.id #error
# car.create_loan
end
end
factory :loan
initial_amount Faker::Number.number(5)
start_date Faker::Date.backward(15)
stop_date Date.tomorrow
installment_amount 1000
end
更新
当我使用factory girl associations
时,我会获得PG::NotNullViolation error
factory :car
model Faker::GameOfThromes.house
manufactoring_plant Faker::StarWars.planet
loan
end
结果
An error occurred in a `before(:suite)` hook.
Failure/Error: FactoryGirl.lint
FactoryGirl::InvalidFactoryError:
The following factories are invalid:
* car - PG::NotNullViolation: ERROR: null value in column "car_id" violates not-null constraint
DETAIL: Failing row contains (1, 1453, null, 2016-11-04 10:29:05.4881, 2016-11-04 10:29:05.4881, 2016-11-04, 2000-01-01, null, null, 9588, 1162, ).
: INSERT INTO "loans" ("start_date", "stop_date", "initial_amount", "installment_amount", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $7) RETURNING "id" (ActiveRecord::StatementInvalid)
* loan - PG::NotNullViolation: ERROR: null value in column "car_id" violates not-null constraint
DETAIL: Failing row contains (2, 1453, null, 2016-11-04 10:29:05.49128, 2016-11-04 10:29:05.49128, 2016-11-04, 2000-01-01, null, null, 9588, 1162, 0, f).
外键具有所有标准名称,例如car_id
,为什么factory girl
无法创建关联?