[英]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.我的 Rails 航班预订应用程序有 2 张桌子 - 一张用于航班,一张用于机场。 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).
我正在尝试通过播种来注入飞行和机场数据,并在播种以下飞行数据时不断收到外键约束错误(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.
我尝试使用 model 关联,但我不太确定这是否是问题的根源。
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
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.在运行
rake db:seed
后调用 Airport.delete_all 删除了我所有的机场实例并创建了新的但不同的 id。 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].我不得不重置数据库中的一些序列,例如@muistooshort 建议在此处使用 active-record-reset-pk-sequence gem [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!在
Airport.delete_all
下,我在安装 gem 后添加了Airport.reset_pk_sequence
并且它起作用了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.