rueeazy
rueeazy

Reputation: 119

Foreign Key Constraint Failing - Rails db migration

I have a 2 tables for my rails flight booker application - one for Flight and one for airports. I'm trying to pump in flight and airport data via seeding and keep getting a foreign key constraint error when seeding flight data below (rake db:seed). I tried playing around with the model associations but I'm not quite sure if that's the source of the problem.

Tables

Flight(id: integer, start_airport_id: integer, end_airport_id: integer, departure_time: datetime, flight_duration: integer, created_at: datetime, updated_at: datetime)

Airport(id: integer, airport_code: string, created_at: datetime, updated_at: datetime)

Seed File

Airport.delete_all
airports = Airport.create([{ airport_code: 'SFO' }, { airport_code: 'NYC' }, { airport_code: 'LAX' }, 
{ airport_code: 'LAS' }, { airport_code: 'DEN' }, { airport_code: 'SEA' }, {airport_code: 'PHX' }])

Flight.delete_all
flights = Flight.create([{ start_airport_id: 1, end_airport_id: 2, departure_time: DateTime.new(2020, 8, 29, 16, 30, 0), flight_duration: 5 }, 
{ start_airport_id: 1, end_airport_id: 3, departure_time: DateTime.new(2020, 7, 13, 13, 0, 0), flight_duration: 2 }, 
{ start_airport_id: 1, end_airport_id: 4, departure_time: DateTime.new(2020, 9, 7, 9, 30, 0), flight_duration: 2 }, 
{ start_airport_id: 2, end_airport_id: 7, departure_time: DateTime.new(2020, 10, 6, 10, 0, 0), flight_duration: 5 }, 
{ start_airport_id: 1, end_airport_id: 2, departure_time: DateTime.new(2020, 12, 4, 6, 30, 0), flight_duration: 6 }, 
{ start_airport_id: 3, end_airport_id: 2, departure_time: DateTime.new(2020, 11, 4, 11, 0, 0), flight_duration: 6 }])

Models

class Airport < ApplicationRecord
    has_many :departing_flights, class_name: "Flight"
    has_many :arriving_flights, class_name: "Flight"
end

class Flight < ApplicationRecord
    has_many :to_airport, foreign_key: :end_airport_id, class_name: "Airport"
    has_many :from_airport, foreign_key: :start_airport_id, class_name: "Airport"
end

Upvotes: 0

Views: 233

Answers (1)

rueeazy
rueeazy

Reputation: 119

Solved it! Calling Airport.delete_all after running rake db:seed deleted all my instances of airports and created new ones but different id's. I had to reset some sequences in the db like @muistooshort suggested using the active-record-reset-pk-sequence gem here [https://github.com/splendeo/activerecord-reset-pk-sequence] . Below Airport.delete_all I added Airport.reset_pk_sequence after installing the gem and it worked!

Upvotes: 1

Related Questions