外键约束失败-Rails数据库迁移

时间:2020-07-09 22:38:09

标签: ruby-on-rails ruby foreign-keys migration model-associations

我有2张桌子供我的Rails Flight Booker应用程序使用-一张用于飞行,一张用于机场。我正在尝试通过播种来抽取飞行和机场数据,并在以下播种飞行数据时保持外键约束错误(rake db:seed)。我尝试玩弄模型关联,但是我不确定这是否是问题的根源。

表格

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)

种子文件

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 }])

模型

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

1 个答案:

答案 0 :(得分:1)

解决了!运行rake db:seed后调用Airport.delete_all删除了我所有的机场实例,并创建了新的实例,但ID不同。我不得不在数据库中重置一些序列,例如@muistooshort,建议在此处使用active-record-reset-pk-sequence gem [https://github.com/splendeo/activerecord-reset-pk-sequence]。在Airport.delete_all 下,我在安装gem后添加了Airport.reset_pk_sequence,它可以正常工作!