0

I followed the advice of this SO post. An entree belongs_to a venue. So I expect a foreign key named venue_id on the entrees table. I generated the following:

rails g migration AddEntreeToVenue entree:belongs_to 

It created the following migration:

class AddEntreeToVenue < ActiveRecord::Migration[5.0]
  def change
    add_reference :venues, :entree, foreign_key: true
  end
end

But after running db:migrate, I look at the entrees table and no foreign key:

Indexes:
    "entrees_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "venues" CONSTRAINT "fk_rails_0cf11999c6" FOREIGN KEY (entree_id) REFERENCES entrees(id)

What it appeared to do was add the foreign key to the venues table, not the entrees table. What did I do wrong?

Daniel Viglione
  • 8,014
  • 9
  • 67
  • 101
  • You should have added the reference to the entrees table. Do: add_reference :entrees, :venue, index: true – bkunzi01 Sep 20 '17 at 23:52

1 Answers1

1

Your generator command specified that Rails should create a belongs_to column on Venues. What you actually want is the opposite:

rails g migration AddVenueToEntrees venue:belongs_to

This will create a migration that modifies entrees, adding a venue_id column with a foreign key constraint on venues.id.

coreyward
  • 77,547
  • 20
  • 137
  • 166