How to add field in existing table phoenix
Asked Answered
P

1

19

So I'm a newbie in phoenix. I created a simple api in my phoenix project the problem is that i want to add another field in my todo.ex

I want to add an author field in my todo.ex

FROM

defmodule TodoApi.Todo do
  use TodoApi.Web, :model

  schema "todos" do
    field :description, :string

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:description])
    |> validate_required([:description])
  end
end

TO

defmodule TodoApi.Todo do
  use TodoApi.Web, :model

  schema "todos" do
    field :description, :string
    field :author, :string

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:description, :author])
    |> validate_required([:description, :author])
  end
end

But I'm getting an postgrex error 42703 column t0.author does not exist

Thanks in advance..

Patience answered 29/1, 2018 at 5:2 Comment(0)
M
38

You need to add a migration for todos table.

If you use ecto, just generate a migration using mix ecto.gen.migration todos_add_author_column and add a column in the newly generated priv/repo/migrations/<timestamp>_todos_add_author_column.exs file like this :

def change do
  alter table("todos") do
    add :author, :text
  end
end

Here's a link to docs

Manipular answered 29/1, 2018 at 5:50 Comment(6)
So i need to create another file for this ?? then execute ecto.migrate ?Patience
You can execute mix task mix ecto.gen.migration todos_add_author_column. It will generate the migration file for you. You will just need to populate its change functionManipular
Thanks i've successfully gen and migrated the author field the problem now is i can't seem to add data using postman its only adding the description not the author.Patience
@Priz, is your TodoApi.Todo module exactly the same as in the question?Manipular
Yes its exactly the samePatience
Let us continue this discussion in chat.Manipular

© 2022 - 2024 — McMap. All rights reserved.