【问题标题】:Seeding a database with "flights"用“航班”播种数据库
【发布时间】: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


【解决方案1】:

这是一个常见错误,有两个修复方法。

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 会尽力帮助您,但您必须为其提供正确的对象类型。

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 2015-09-25
    • 2017-07-14
    • 1970-01-01
    • 2015-06-29
    • 2014-03-01
    • 2018-12-14
    • 2018-05-20
    相关资源
    最近更新 更多