【发布时间】:2017-12-02 22:32:28
【问题描述】:
我正在尝试为我的数据库添加种子,但我不断收到错误消息“ActiveRecord::RecordInvalid: Validation failed: Arriving flight must exist”。在我在seeds.rb 文件中创建关联的方法中,我提供了arrival_airport_id,所以我不确定问题出在哪里。
种子.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] 更改为arrival_airport_id: b[index].id 并且它有效,但我认为rails 已经知道这样做了吗?
-
如果您认为您解决了问题,您可以回答您的问题并帮助其他人。
-
我打算这样做,但我不确定这是否是正确的解决方法。我想我会看看其他人会怎么做。
标签: ruby-on-rails ruby database validation