How to Add a Field to a Generated Table Retroactively

From ElixirBlocks
Revision as of 15:31, 19 June 2023 by Admin (talk | contribs)
Jump to: navigation, search

This page is in progress


First, generated data is created. This is an example:


mix phx.gen.html TestBeds TestBed  testbeds name:string url:string

Generate a migration file

To add a field, you must first generate a migration file. The migration file is an empty file that is generated using a console command. After it is generated you write code and invoke it.

The command is:

mix ecto.gen.migration name_of_migration

For this example, I will add a new field named owner

mix ecto.gen.migration create_owner_field

The migration file after it is created appears in app/priv/migrations


You need to type code that does what you want.

To add a field you write code like the following. Here we add a field named owner.


  def change do
    alter table(:testbeds) do    # customize to your code
      add :owner, :string
    end
  end

You can also re-name a pre-existing table field.

  def change do
    rename table("testbeds"), :url, to: :owner
  end

In the terminal run:

mix ecto.migrate

The field is created but the HTML, controllers and tests are not. You need to manually replicate that code. Use prerecreated Generated field code as a reference.