用“航班”播种数据库

时间:2017-12-02 22:32:28

标签: ruby-on-rails ruby database validation

我正在尝试播种我的数据库并且我一直收到错误“ActiveRecord :: RecordInvalid:验证失败:到达航班必须存在”。在我的seed.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

1 个答案:

答案 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列,也可以将对象分配给object列。

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

Rails尝试尽力帮助你,但你必须给它正确的对象类型。