Rails5 - 在 postgres 中向现有模型添加外键

Rails5 - Adding Foreign Keys to Existing Models in postgres

我有两个模型。一个 Events 模型和一个 EventOptionEventshave_many :event_options

我的问题是,当我尝试迁移到 add_foreign key :event_options, :events 以便我可以 link 它们时,我收到以下错误:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "event_id" referenced in foreign key constraint does not exist
: ALTER TABLE "event_options" ADD CONSTRAINT "fk_rails_3995702fad"
FOREIGN KEY ("event_id")
  REFERENCES "events" ("id")

这是我的 schema.rb:

ActiveRecord::Schema.define(version: 20160806001743) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "event_options", force: :cascade do |t|
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.float    "price"
    t.text     "description"
    t.string   "name"
  end

  create_table "events", force: :cascade do |t|
    t.datetime "created_at",                null: false
    t.datetime "updated_at",                null: false
    t.string   "name"
    t.boolean  "active",     default: true
  end

  create_table "users", force: :cascade do |t|
    t.datetime "created_at",                     null: false
    t.datetime "updated_at",                     null: false
    t.string   "email",                          null: false
    t.string   "encrypted_password", limit: 128, null: false
    t.string   "confirmation_token", limit: 128
    t.string   "remember_token",     limit: 128, null: false
    t.index ["email"], name: "index_users_on_email", using: :btree
    t.index ["remember_token"], name: "index_users_on_remember_token", using: :btree
  end

end

我知道有 :id 列可以工作,因为我可以在控制台中使用它们。我知道我在这里缺少一些东西来让外键为应用程序工作,但对于我的生活,我不知道是什么。

等等,你的意思是 has_many 的外键选项,这不是 add_foreign_key 令人困惑的地方。它添加了一个外键约束。

因此在您的迁移中,您需要先 add_columnadd_reference

add_reference :event_options, :event, index: true 
add_foreign_key :event_options, :events