我有两个型号。 Events
模型和EventOption
。 Events
将have_many
:event_options
。
我的问题是,当我尝试迁移到add_foreign key :event_options, :events
以便我可以将它们链接起来时,我收到以下错误:
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列有效,因为我可以在控制台中使用它们。我知道我在这里错过了一些东西让外键为应用程序工作,但对于我的生活,我不知道是什么。
答案 0 :(得分:4)
等等,你的意思是has_many的外键选项,这不是add_foreign_key
令人困惑的问题。它添加了一个外键约束。
因此,在迁移过程中,您需要先add_column
或add_reference
add_reference :event_options, :event, index: true
add_foreign_key :event_options, :events