关于约束错误的令人困惑的错误消息

confusing error message on constraint error

Ecto 向我抛出以下错误:

** (exit) an exception was raised:
    ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * unique: res_users_login_key

If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:

    * unique: res_users_login_index

我是否理解正确,postgresql 中约束的实际名称决定了 unique_constraint/3 函数是否成功?仅供参考,在 postgreSQL 中,约束定义如下:

Indexes:
    "res_users_pkey" PRIMARY KEY, btree (id)
    "res_users_login_key" UNIQUE CONSTRAINT, btree (login)

所以 _key 而不是 _index

我调用约束函数如下:

 changeset |> unique_constraint(:login)

那么,我该怎么做呢?

Ecto 在没有给出时使用的约束名称是#{table_name}_#{field}_index。你的 table 可能被命名为 res_users,字段是 login,这就是 Ecto 使用约束名称 res_users_login_index 的原因,这在你的情况下是不正确的。您需要在 unique_constraint:

的调用中明确指定名称 res_users_login_key
|> unique_constraint(:login, [name: :res_users_login_key])