Haito
Haito

Reputation: 2069

Ecto add/3 default not working properly

I have trouble with getting default value to use. I believe that I have set it up properly but it doesn't seem to work. When queried, new records have none (nothing, blank space) in the PGAdmin instead of supposed 0.

Migration:

    create table(:teachers) do
      add :login, :string
      add :password, :string
      add :email, :string
      add :role, :integer, default: 0

      timestamps
    end

Model:

defmodule Ep.Teacher do
  use Ep.Web, :model

  schema "teachers" do
    field :login, :string
    field :password, :string
    field :email, :string
    field :role, :integer

    has_many :tests, Ep.Test, on_delete: :fetch_and_delete

    timestamps
  end

  @required_fields ~w(login password email)
  @optional_fields ~w(role)

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

PGAdmin table stats:

CREATE TABLE public.teachers
(
  id integer NOT NULL DEFAULT nextval('teachers_id_seq'::regclass),
  ....
  role integer DEFAULT 0,
  ....
  CONSTRAINT teachers_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.teachers
  OWNER TO postgres;

Controller:

 def create(conn, %{"teacher" => teacher_params}) do
    IO.inspect teacher_params
    changeset = Teacher.changeset(%Teacher{}, teacher_params)
    case Repo.insert(changeset) do
      {:ok, _teacher} ->
        conn
        |> put_flash(:info, "Teacher created successfully.")
        |> redirect(to: teacher_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

Upvotes: 2

Views: 253

Answers (1)

arunvelsriram
arunvelsriram

Reputation: 1096

In the model you will have to add default: 0 as given below:

defmodule Ep.Teacher do
  use Ep.Web, :model

  schema "teachers" do
    field :login, :string
    field :password, :string
    field :email, :string
    field :role, :integer, default: 0

    has_many :tests, Ep.Test, on_delete: :fetch_and_delete

    timestamps
  end

  @required_fields ~w(login password email)
  @optional_fields ~w(role)

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

Upvotes: 2

Related Questions