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會知道這樣做嗎? –
如果你認爲你解決了這個問題,你可以回答你的問題和幫助其他人。 –
我打算去,但我不確定這是否是正確的修復方法。我想我會看到別人會如何去做。 –