How do you change the db schema?

Hi,

I am still very new to Elixir/Phoenix/Ecto. I have a question regarding migrations. You can use a command

$ mix phoenix.gen.html User users name:string email:string bio:string number_of_pets:integer
$ mix ecto.migrate

to generate the Ecto model. This command generates the initial migration file for you. Now if I want to say add a new field to this model (for e.g. “address:string”), how do I go about doing it? Please tell me if I am doing something wrong here

  1. Create a new migration file named YYYYMMDDSSSSSS_alter_users.exs in repo/migrations directory with contents as follows

    defmodule HelloPhoenix.Repo.Migrations.AlterUser do
    use Ecto.Migration

    def change do
    alter table(:users) do
    add :address, string
    add :usertype_id, references(:usertypes, on_delete: :nothing)
    end
    end

  2. run $mix ecto.migrate

How will Ecto know to not run other migration files already in the repo/migrations directory? I don’t want to run something and find out that I messed up big time.

Thanks
Sudheer

If you check your database you will see that Ecto created a table of its own called schema_migrations, and it is this table that holds meta information about what state the database schema is in (consequently, never touch this table manually).

Your migration looks good.

You can use mix ecto.gen.migration to create the file for you. See mix help ecto.gen.migration for more information.

@OvermindDL1 and @dsissitka: Thanks for the quick reply. That gave me a relief.

Sudheer