11

I have already existing foreign key in database created this way:

class CreateUser < ActiveRecord::Migration
  def change
    create_table do ... end
    add_foreign_key :users, :admins, column: :admin_id
  end
end

but forgot to add on_delete: :nullify. Migration is already pushed & used on production. I want to add new migration which will add cascale deleting for this PK constraint. How to achieve that?

Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102

1 Answers1

15

You can remove and add foreign key in next migration:

class ChangeForgeinKeyOnUsersTable < ActiveRecord::Migration[5.0]
  def change
    remove_foreign_key :users, column: :admin_id
    add_foreign_key :users, :admins, column: :admin_id, on_delete: :nullify
  end
end
Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
  • 1
    also: if column is already populated with data don't forget to migrate data as well (i.e. select all and then insert all) – Filip Bartuzi Oct 24 '17 at 12:08
  • 1
    @RicardoGreen what I would do: 1. rename column (admin_id -> admin_id_copy); 2. add new column with name "admin_id", this time with constraint. 3. Copy data from admin_id_copy to admin_id column (you can just iterate in migration through collection :) but remember it will take a while for big DB). 4. drop admin_id_copy table – Filip Bartuzi Aug 13 '19 at 07:59
  • Is migrating the data really necessary? I think this drops just the contraint, not the whole column (data). An alternative approach I used is to do everything directly in SQL (Postgres specific): https://stackoverflow.com/questions/10356484/how-to-add-on-delete-cascade-constraints – Malte Apr 03 '21 at 15:25