MajSB
MajSB

Reputation: 11

FactoryGirl has_many association

I have the following error when trying to use FactoryGirl to create a flight with 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" 

My model is as below :

flight.rb

 belongs_to :customer

customer.rb

has_many :flights

And here is what I have in 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

Do you see why it is not working ?

Thanks

Upvotes: 1

Views: 272

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

I think that what you are looking looks more like this

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

you can see this code working from this sample app https://github.com/mzaragoza/sample_factorygirl_with_has_many_association

Upvotes: 1

Related Questions