GeekFitness GeekFitness - 3 months ago 7
Ruby Question

Rails5 - Adding Foreign Keys to Existing Models in postgres

I have two models. An

Events
model and an
EventOption
. The
Events
will
have_many
:event_options
.

My issue is that when I try to do a migration to
add_foreign key :event_options, :events
so that I can link them up, I get the following error:

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")


Here's my 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


I know there are :id columns that work because I can play with them in the console. I know I'm missing something here to get the Foreign Keys working for the app, but for the life of me, I don't know what.

Answer

Wait, you mean the foreign key option for the has_many, that isn't what add_foreign_key does confusingly. It adds a foreign key constraint.

So in your migration you need to do add_column or add_reference first

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