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.
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
def change do
alter table("puppies") do
add :dog_id, references(:dogs)
# 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])
Edit: you’ll find extensive informations on Ecto migrations in the offical docs:
Ecto.Migration — Ecto SQL v3.5.4
Great, thank you! That works!!