0
我想种子我的数据库,我不断收到错误“ActiveRecord :: RecordInvalid:验证失败:到达航班必须存在”。在我的用于在我的seeds.rb文件中创建关联的方法中,我提供了arrival_airport_id,所以我不确定问题是什么。播种数据库与“航班”
seeds.rb
Airport.delete_all
Flight.delete_all
#Airport seeds
airports = [
["Boston Logan International Airport", "BOS"],
["Gulfport", "GPT"],
["Jackson", "JAN"],
["Charleston", "CRW"]
]
airports.each do |full_name, name|
Airport.create!(full_name: full_name, name: name)
end
a = Airport.all[0..1]
b = Airport.all[2..3]
a.each_with_index do |a, index|
a.departing_flights.create!(
arrival_airport_id: b[index]
)
end
机场模型:
class Airport < ApplicationRecord
has_many :departing_flights, class_name: "Flight", foreign_key: "departing_airport_id"
has_many :arriving_flights, class_name: "Flight", foreign_key: "arrival_airport_id"
end
飞行模式:
class Flight < ApplicationRecord
belongs_to :departing_flight, class_name: "Airport", foreign_key: "departing_airport_id"
belongs_to :arriving_flight, class_name: "Airport", foreign_key: "arrival_airport_id"
end
我改变了arrival_airport_id:b [index] to arrival_airport_id:b [index] .id,它工作,但我认为rails会知道这样做吗? –
如果你认为你解决了这个问题,你可以回答你的问题和帮助其他人。 –
我打算去,但我不确定这是否是正确的修复方法。我想我会看到别人会如何去做。 –