Useful Migrations commands in Phoenix

Sis Ccr
Dec 19, 2020

--

Migrations

Make a field nullable

mix ecto.gen.migration add_nullable_to_field

def change do
alter table(:events) do
modify(:title, :string, null: true, from: :string) # Title column is now nullable
end
end

Add field to existing table

mix ecto.gen.migration add_is_super_admin_to_merchant

Add references to existing table

mix ecto.gen.migration add_district_id_to_room

defmodule Tailwind.Repo.Migrations.AddedDistrictIdToRoom do   use Ecto.Migration
def change do
alter table :rooms do
add :district_id, references( :districts, on_delete: :delete_all)
end
end
end

Add Unique index to a field

I forgot to add unique constraint in email. so generating a migration to add constraint in email.

mix ecto.gen.migration add_uniq_constraint_to_email_on_merchant

Then do mix ecto.migrate

if you got error like “Key (email)=(abc@abc.com) is duplicated.”, that means you already have multiple values in database of same email. Remove those duplicate values and run the migrate command again.

We also need to add unique constraint for email in model .

--

--

Sis Ccr
Sis Ccr

Written by Sis Ccr

Depths of ocean could not swallow me.

No responses yet