2017-12-02 164 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试图帮助你走出它最好的,但你必须给它合适的对象类型。