播种数据库与“航班”

我想种子我的数据库,我不断收到错误“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

回答:

这是一个常见的错误有两种修复。

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

以上是 播种数据库与“航班” 的全部内容, 来源链接: utcz.com/qa/258638.html

回到顶部