我无法获取默认值。我相信我已经正确设置但它似乎不起作用。查询时,新记录在PGAdmin中没有(没有任何空格),而不是假设为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表统计信息:
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
答案 0 :(得分:2)
在模型中,您必须添加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