Dave
Dave

Reputation: 19150

How do I create a foreign key with a cascading delete constraint in my Rails 5 migration?

I'm using Rails 5 with PostGres 9.5 . I want to create a foreign key to my addresses table from my search_codes table so I created this migration

class CreateSearchCodeTable < ActiveRecord::Migration[5.0]
  def change
    create_table :search_codes do |t|
      t.string :code
      t.references :address, type: :string, index: true, foreign_key: true, on_delete: :cascade
      t.index ["code"], name: "index_search_codes_on_code", unique: true, using: :btree
    end
  end
end

However what gets created is the following. Notice the cascading portion of the constraint didn't seem to get created

myapp=> \d search_codes;
                                Table "public.search_codes"
   Column   |       Type        |                         Modifiers
------------+-------------------+-----------------------------------------------------------
 id         | integer           | not null default nextval('search_codes_id_seq'::regclass)
 code       | character varying |
 address_id | character varying |
Indexes:
    "search_codes_pkey" PRIMARY KEY, btree (id)
    "index_search_codes_on_code" UNIQUE, btree (code)
    "index_search_codes_on_address_id" btree (address_id)
Foreign-key constraints:
    "fk_rails_6bd9792e3b" FOREIGN KEY (address_id) REFERENCES addresses(id)

How do I create a migration with a cascading foreign key constraint using the Rails 5 migration and PostGres?

Upvotes: 1

Views: 3963

Answers (2)

Noah
Noah

Reputation: 11

From this link for a previous version of Rails, Option for Cascade Delete for References or On Delete

This t.references :parent, index: true, foreign_key: {on_delete: :cascade}

Seems to work

Edit: note that it also appears you don't need 'index: true'. It creates an index as well.

Upvotes: 1

Hirurg103
Hirurg103

Reputation: 4953

Seems like that ReferenceDefinition doesn't accept on_delete option. You can specify on delete with add_foreign_key:

class CreateSearchCodeTable < ActiveRecord::Migration[5.0]
  def change
    create_table :search_codes do |t|
      t.string :code
      t.references :address, type: :string, index: true
      t.index ["code"], name: "index_search_codes_on_code", unique: true, using: :btree
    end

    add_foreign_key :search_codes, :addresses, on_delete: :cascade
  end
end

Upvotes: 1

Related Questions