How to Add a Field to a Generated Table Retroactively

From ElixirBlocks
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/repo/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 pre-created Generated field code as a reference. You can start by updating the schema and going to name_of_app/lib/name_of_app/name_of_table/name_of_table.ex


You will see the schema and you can update it's data.


defmodule App.TestBeds.TestBed do
  use Ecto.Schema
  import Ecto.Changeset

  schema "testbeds" do
    field(:developer, :string)
    field(:name, :string)
    field(:owner, :string)
    field(:note, :string)
    field(:status, :string)
    field(:url, :string)
    field(:version, :string)
    field(:manager, :string)
    field(:db_backup, :boolean, default: false)
    field(:vnetc_auto_upgrade, :boolean, default: false)
    field(:firmware_auto_upgrade, :boolean, default: false)
    field(:managed_out_of_service, :boolean, default: false)

    timestamps()
  end

  @doc false
  def changeset(test_bed, attrs) do
    test_bed
    |> cast(attrs, [:name, :version, :owner, :note, :developer, :status,:url, :manager, :db_backup,:vnetc_auto_upgrade,:firmware_auto_upgrade,:managed_out_of_service])
    |> validate_required([:name, :status])
  end
end