如何在rails activerecord中为sqlite3数据库种子?

nlejzf6q  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(352)

我试图通过rails activerecord中sqlit3 db上的seed.rb文件填充航班表,代码如下:

departure = Date.new(2021, 9, 1)
   arrival = Date.new(2021, 10, 1)

  (departure).upto(arrival).each do |flight_schedule|
   airports.each do |origin|
    airports.each do |destination|
      if origin == destination
        next
      else
        3.times { Flight.create(origin: origin,
                                destination: destination,
                                flight_schedule: flights_time,
                          duration: flights_duration(origin.code, destination.code))}
      end
     end
    end
   end

我在机场和飞行模型之间建立了多对多关系,参考(外键)如下;

class Airport < ApplicationRecord
    has_many :departures, 
             class_name: :Flight, 
             foreign_key: :origin_id, 
             dependent: :destroy

    has_many :arrivals, 
             class_name: :Flight,  
             foreign_key: :destination_id, 
             dependent: :destroy
end

class Flight < ApplicationRecord
  belongs_to :origin, class_name: :Airport
  belongs_to :destination, class_name: :Airport

end

下面是db模式的示例;

ActiveRecord::Schema.define(version: 2021_07_21_232515) do

  create_table "airports", force: :cascade do |t|
    t.string "code"
    t.string "location"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "flights", force: :cascade do |t|
    t.integer "origin_id", null: false
    t.integer "destination_id", null: false
    t.integer "duration"
    t.datetime "flight_schedule"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["destination_id"], name: "index_flights_on_destination_id"
    t.index ["origin_id"], name: "index_flights_on_origin_id"
  end

  add_foreign_key "flights", "destinations"
  add_foreign_key "flights", "origins"
end

运行rails db:seed时,出现以下错误:

Rails aborted!
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.destinations

rails版本6.1.4 ruby版本3.0.1p64(2021-04-05版本0fb782ee38)[x86_64-linux]

muk1a3rh

muk1a3rh1#

架构看起来不正确, add_foreign_key 应该是这样的

add_foreign_key "flights", "airports", column: "destination_id"
add_foreign_key "flights", "airports", column: "origin_id"

所以我猜您的迁移是不正确的,您应该检查这些迁移相对于添加 referencesforeign_keyflights 表,它应该如下所示:

create_table :flights do |t|
 # ...
 t.belongs_to :origin, null: false
 t.belongs_to :destination, null: false
 # ...
 t.foreign_key :airports, column: :origin_id
 t.foreign_key :airports, column: :destination_id
end

相关问题