FactoryGirl has_many协会

时间:2016-03-06 21:08:28

标签: ruby-on-rails factory-bot has-many

尝试使用FactoryGirl创建p = FactoryGirl.create(:flight)的航班时出现以下错误:

 ActiveRecord::InvalidForeignKey:
   PG::ForeignKeyViolation: ERROR:  insert or update on table "flights" violates foreign key constraint "fk_rails_11f6e1e673"
   DETAIL:  Key (customer_id)=(457) is not present in table "customers".
   : INSERT INTO "flights" ("flight_type", "route", "customer_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" 

我的模型如下:

flight.rb

 belongs_to :customer

customer.rb

has_many :flights

以下是我在Factories.rb中的内容:

factory :customer do
     customer_name 'Customertest'
     contract_type 'true'   
end

factory :flight do
    flight_type 'Medivac'
    route 'A - B - C - A'
    customer
end

你明白为什么它不起作用吗?

由于

1 个答案:

答案 0 :(得分:1)

我认为你看起来更像是这个

FactoryGirl.define do
  factory :flight do
    flight_type { 'Medivac' }
    route { 'A - B - C - A' }
    after(:create) do |flight|
      flight.customer ||= Customer.last || FacoryGril.create(:customer)
    end
  end
end

您可以在此示例应用https://github.com/mzaragoza/sample_factorygirl_with_has_many_association

中看到此代码