2

Ecto is throwing me the following error:

** (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

Do I understand correctly that the actual name of the constraint in postgresql determines if the unique_constraint/3 function is successful or not? Just for reference, in postgreSQL the constraint is defined as follows:

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

so _key and not _index.

I call the constraint function as follows:

 changeset |> unique_constraint(:login)

So, how do I make this work?

5
  • Try |> unique_constraint(:login, [name: :res_users_login_index]). Commented Apr 28, 2017 at 14:22
  • Do you mean: |> unique_constraint(:login, [name: :res_users_login_key])? Commented Apr 28, 2017 at 14:23
  • Oops yes, _key. _index is the incorrect name used by default since you hadn't specified a name. Commented Apr 28, 2017 at 14:29
  • Looking at stackoverflow.com/questions/4107915/… _index seems to be an inappropriate default doesn't it? Seems _key would be better for unique constraints. Commented Apr 28, 2017 at 14:35
  • They probably default to that because unique_index in Ecto migrations use the _index suffix for the index names by default. Commented Apr 28, 2017 at 14:41

1 Answer 1

3

The constraint name used by Ecto when one is not given is #{table_name}_#{field}_index. Your table is probably named res_users, and the field is login, which is why Ecto uses the constraint name res_users_login_index, which is incorrect in your case. You'll need to explicitly specify the name res_users_login_key in the call to unique_constraint:

|> unique_constraint(:login, [name: :res_users_login_key])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.