ruby on rails - Rails5 - Adding Foreign Keys to Existing Models in postgres -
i have 2 models. events
model , eventoption
. events
have_many
:event_options
.
my issue when try migration add_foreign key :event_options, :events
can link them up, following error:
activerecord::statementinvalid: pg::undefinedcolumn: error: column "event_id" referenced in foreign key constraint not exist : alter table "event_options" add constraint "fk_rails_3995702fad" foreign key ("event_id") references "events" ("id")
here's schema.rb:
activerecord::schema.define(version: 20160806001743) # these extensions must enabled in order support database enable_extension "plpgsql" create_table "event_options", force: :cascade |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 |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 |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
i know there :id columns work because can play them in console. know i'm missing here foreign keys working app, life of me, don't know what.
wait, mean foreign key option has_many, isn't add_foreign_key
confusingly. adds foreign key constraint.
so in migration need add_column
or add_reference
first
add_reference :event_options, :event, index: true add_foreign_key :event_options, :events
Comments
Post a Comment