Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add :on_delete to already existing foreign_key in rails migration

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?

like image 401
Filip Bartuzi Avatar asked Aug 24 '16 08:08

Filip Bartuzi


1 Answers

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
like image 88
Filip Bartuzi Avatar answered Sep 23 '22 16:09

Filip Bartuzi