Adding new column(reference) to existing table

I generated a migration using mix phx.gen.schema (Dogs)

I then created a new migration (Puppies). I would like to create a new migration and alter Puppies migration by adding a belongs_to relationship to Dogs.

I tried mix ecto.gen.migration puppies_add_dog_id_column. This creates a migration but how do I add reference to an existing table while migration? Or is this command even the right way to do it? Any suggestion is appreciated.

The command is fine, you have to write the actual migration yourself then, i.e. to add a foreign key referencing the dogs table you could do:

defmodule YourApp.Repo.Migrations.PuppiesAddDogIdColumn do
  use Ecto.Migration

  def change do
    alter table("puppies") do
      add :dog_id, references(:dogs)
    end

    # if you want the index -and why not wanting it? ;) 
    # pls note this is after the `alter` macro, and inside the `change` callback def
    create index(:puppies, [:dog_id])
  end
end

hth

Edit: you’ll find extensive informations on Ecto migrations in the offical docs:
Ecto.Migration — Ecto SQL v3.5.4

3 Likes

Great, thank you! That works!!