Setting unique_constraint Ecto

I have a user model with an email field. Now I would like to make it unique, therefore, according to the documentation, I need to apply:

cast(user, params, ~w(email), ~w()) |> unique_constraint(:email) 

In addition, I have to define a unique index in the migration:

 create unique_index(:users, [:email]) 

The problem is that when I tried to determine this during the migration, adding a few more fields, it didn’t work, and now I try to just define the transfer using this create unique_index(:users, [:email]) and this creates an error:

 [info] create index users_email_index ** (Postgrex.Error) ERROR (unique_violation): could not create unique index "users_email_index" 

What am I doing wrong?

+7
elixir phoenix-framework ecto
source share
1 answer

This can happen when a unique constraint is already violated in your table.

Please check that you do not yet have duplicate email addresses in your users table.

You can run mix do ecto.drop, ecto.create, ecto.migrate to delete and recreate the database and tables.

+11
source share

All Articles