Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting unique_constraint Ecto

I have have a User model with an email field. Now I would like to make it unique, so, as per documentation, I need to apply:

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

Also, I should define the unique index in a migration:

create unique_index(:users, [:email])

The problem is that when I tried to define this in a migration while adding some more fields it didn't work and now I'm trying to just define a migration with this create unique_index(:users, [:email]) and it's creating 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?

like image 761
Paulo Janeiro Avatar asked Sep 04 '15 12:09

Paulo Janeiro


People also ask

What is ecto setup?

setup , Ecto tries to create the repository database, load the database structure present in the structure. sql file, run any pending migrations and finally run the seeds. However, unfortunately, it doesn't work in Ecto SQL versions before 3.1.

Is Ecto an ORM?

Unlike ActiveRecord, Ecto is not an ORM, but a library that enables the use of Elixir to write queries and interact with the database. Ecto is a domain specific language for writing queries and interacting with databases in Elixir.


1 Answers

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

Please check that you do not already 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.

like image 187
Gazler Avatar answered Oct 13 '22 01:10

Gazler