I am getting this red exception error despite the fact that I’m using unique_constraint/3:
** (Ecto.ConstraintError) constraint error when attempting to insert struct:
* join_lessons_resources_pkey (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.
I updated my migration to use a name:
def change do
drop unique_index(:join_lessons_resources, [:lesson_id, :resource_id])
create unique_index(:join_lessons_resources, [:lesson_id, :resource_id], name: :lesson_resource_index)
end
Then I updated my schema to use a name:
def changeset(join_lesson_resource, attrs) do
join_lesson_resource
|> cast(attrs, [:lesson_id, :resource_id])
|> validate_required([:lesson_id, :resource_id])
|> unique_constraint([:lesson_id, :resource_id], name: :lesson_resource_index)
end
The code that is passing the ids to be checked is using a changeset:
join =
JoinLessonResource.changeset(
%JoinLessonResource{}, %{lesson_id: lesson_id, resource_id: resource_id})
Repo.insert(join)
I emptied my database (which only had 4 entries so it was no big deal). I then entered a new entry and it worked fine. I then tried to enter the same entry (same lesson_id and same resource_id) and i got the error above. As far as I can tell, I’m doing everything correctly in terms of using unique_constraint/3.
Why is it raising an red exception with Ecto.ConstraintError instead of returning an error in my changeset??