2017-12-02 163 views
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 
+2

我改變了arrival_airport_id:b [index] to arrival_airport_id:b [index] .id,它工作,但我認爲rails會知道這樣做嗎? –

+0

如果你認爲你解決了這個問題,你可以回答你的問題和幫助其他人。 –

+0

我打算去,但我不確定這是否是正確的修復方法。我想我會看到別人會如何去做。 –

回答

0

這是一個常見的錯誤有兩種修復。

a.each_with_index do |a, index| 
    a.departing_flights.create!(
    arrival_airport_id: b[index] # This line is the problem 
    ) 
end 

您正在將一個對象分配給一個id列。您可以將id分配給id列或將對象分配給對象列。

arrival_airport_id: b[index].id 
# or 
arrival_airport: b[index] 

的Rails試圖幫助你走出它最好的,但你必須給它合適的對象類型。