2
votes

I've created a simple user model using phoenix.gen.html with the schema produced in models/user.ex as follows.

    schema "users" do
      field :name, :string
      field :email, :string
      field :bio, :string
      field :dislikes_turnips, :boolean

      timestamps
  end

Along with models/user.ex, the database table has been created along with the views, controllers and templates.

I'd like to update my User Model by changing one field and adding another to the create something like the following.

schema "users" do
    field :name, :string
    field :email, :string
    field :bio, :string
    field :likes_turnips, :boolean
    field :turnips, :integer

    timestamps
  end

Is there a mix task or similar to update the related database table, views, controllers and templates in one go?

And if not, what would be the recommended process to change/update these files?

1

1 Answers

3
votes

You will need to make the updates to your scheme as you have done. However you will also need to generate a migration so your database table reflects this:

mix ecto.gen.migration change_turnips_on_users

You should have a new file in priv/repo/migrations that you need to modify (you an read more about migrations in the docs:

defmodule MyApp.Repo.Migrations.ChangeTurnipsOnUsers do
  use Ecto.Migration

  def change do
    alter table(:users) do
      add :turnips, :integer
    end

    rename table(:users), :dislikes_turnips, to: :likes_turnips
  end
end

You will also need to update the following things:

  • form.html.eex for your user
  • The changeset/2 function that was generated for your user model to reflect the new fields.