Migration for changing on_delete option on references column

Viewed 1662

I was playing with Phoenix and making has_many associations. I usually do on_delete: :delete_all as an option to the reference column. But if I change my mind and want to change it later for nilify_all, is there a way to this with inside a migration?

Migration for creating the table:

  def change do
    create table(:messages) do
      add :body, :text
      add :sender_id, references(:users, on_delete: :delete_all)

      timestamps()
    end
    create index(:messages, [:sender_id])

  end

I'm looking for something like this:

def change do
  change_options table(:messages), :user_id, on_delete: :nilify_all
end

I've seen modify and alter but I didn't see anything about on_delete. Maybe it's not possible via migrations?

2 Answers

This Elixir Forum post notes that modify() can take a :from option; this lets you use change instead of up/down, and it will drop the previous constraint for you:

def change do
  alter table(:messages) do
    modify :sender_id, references(:users, on_delete: :nilify_all),
      from: references(:users, on_delete: :delete_all)
  end
end
Related