**My ‘users’ table uses a ‘uname’ field unique constraint, and when I tried to insert the same ‘uname’ repeatedly, changeset didn’t give me any duplicate constraint information, but it was directly constrained by the database and failed. From what I can see from the documentation, it seems like he should be able to determine the repeated errors in changeset himself and return the information I defined. **
What am I doing wrong?
My dev env
Win 11
postgre 12
Elixir 1.71.1
{:ecto_sql, “~> 3.12.0”},
{:postgrex, “~> 0.19.1”}
** (Ecto.ConstraintError) constraint error when attempting to insert struct:
* "users_uname_index" (unique_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call unique_constraint/3
on your changeset with the constraint
:name
as an option.
The changeset has not defined any constraint.
(ecto 3.12.3) lib/ecto/repo/schema.ex:878: anonymous fn/4 in Ecto.Repo.Schema.constraints_to_errors/3
(elixir 1.17.1) lib/enum.ex:1703: Enum."-map/2-lists^map/1-1-"/2
(ecto 3.12.3) lib/ecto/repo/schema.ex:862: Ecto.Repo.Schema.constraints_to_errors/3
(ecto 3.12.3) lib/ecto/repo/schema.ex:839: Ecto.Repo.Schema.apply/4
(ecto 3.12.3) lib/ecto/repo/schema.ex:415: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
(friends 0.1.0) lib/friends/webapi/http_post_handler.ex:102: WebApi.HttpPostHandler.do_sign_up/1
My schema
schema "users" do
field :uid, :string
field :uname, :string
field :pword, :string
timestamps(type: :utc_datetime)
end
def changeset(users, attrs \\%{}) do
users
|> Ecto.Changeset.cast(attrs, [:uid, :uname, :pword])
|> Ecto.Changeset.validate_required([:uid, :uname, :pword])
|> Ecto.Changeset.unique_constraint(:uname, message: "Username already been exist")
end
My migration
create table(:users) do
add :uid, :string, null: false
add :uname, :string, null: false
add :pword, :string, null: false
timestamps(type: :utc_datetime)
end
create unique_index(:users, [:uname])