Ecto add/3 默认无法正常工作

Ecto add/3 default not working properly

我无法获取要使用的默认值。我相信我已经正确设置了它,但它似乎不起作用。查询时,新记录在 PGAdmin 中有 none(无,空白 space)而不是假设的 0.

迁移:

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

      timestamps
    end

型号:

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 统计数据:

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;

控制器:

 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

在模型中,您必须添加 default: 0,如下所示:

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