Skip to content

Instantly share code, notes, and snippets.

@kelcecil
Last active August 27, 2021 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelcecil/3e07f39ac26edd3668b0ef7f04a2c67a to your computer and use it in GitHub Desktop.
Save kelcecil/3e07f39ac26edd3668b0ef7f04a2c67a to your computer and use it in GitHub Desktop.
Altering a table to add a new field

As mentioned at the end of class, you're now equipped with everything you need to know to add a new field our app with one exception. Our first database migration used the create/2 function to create the table and add our initial fields. We need to use the alter/2 function make modifications such as adding/modifying/or removing fields.

You can run mix ecto.gen.migration add_new_field to get something that looks like this (pay close attention to the snake case in add_new_field):

defmodule AnnieMae.Repo.Migrations.AddNewField do
  use Ecto.Migration

  def change do
    alter table("anime") do
      add :genre, :string
    end
  end
end

Notice my addition of the alter/2 function in the migration. Once you've made your change, you can run mix ecto.migrate to apply your migration to your database. If you change your mind, you can use mix ecto.rollback to unapply the migration from your database.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment