2016-03-06 60 views
1

我有以下错误,当试图使用FactoryGirl创建具有p = FactoryGirl.create(:flight)航班:FactoryGirl的has_many协会

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 

你明白为什么它不工作?

感谢

+0

所以你想做的事是当你创建**航班**其与**客户关联** – MZaragoza

回答

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

+0

感谢您的回复,但是当我尝试我现在​​得到以下错误失败/错误:p = FactoryGirl.create(:flight) ActiveRecord :: StatementInvalid: PG :: NotNullViolation:错误:列“customer_id”中的空值违反了非空约束 :INSERT INTO“flights”(“flight_type”,“route”,“created_at”,“updated_at”)VALUES $ 1,$ 2,$ 3,$ 4)RETURNING“id” – MajSB

+0

非常感谢您的帮助! :D – MajSB

+0

我们都是从同一点开始的。我只是想让我的老师感到骄傲 – MZaragoza