Add: on_delete to already existing foreign_key in rails migration

I already have a foreign key in the 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 being pushed and used in production. I want to add a new migration that will add cascale deletion for this PK restriction. How to do it?

+4
source share
1 answer

You can delete and add the foreign key in the following 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
+5
source

Source: https://habr.com/ru/post/1652300/


All Articles