Ecto foreign_key_constraint throwing error even though it's in the changesset

Hi Everyone :slight_smile:

I’m having a bit of trouble with has_many foreign key relationships in Ecto, I’ve followed the instructions but with no luck. I’ve added the foreign_key_constraint to the changeset, so I’m expecting an {:error, _} tuple, but i’m getting an uncaught Ecto.ConstraintError

My migration:

My Post Changeset

The Error:

Any help would be appreciated in resolving this, thanks :smiley:

Found the Solution:

TLDR: Pipe your struct into a changeset first haha :smiley:

Incorrect:
post |> Api.Org.Repo.delete()

Correct:
post |> Api.Assets.Post.changeset(%{}) |> Api.Org.Repo.delete()

Explanation
Ecto’s constraints_to_errors function uses the changeset to detect the constraints, however because I piped my struct directly into the Repo.delete function instead of passing it to a changeset first, the constraint I set was never picked up

Screenshot From Ecto:

1 Like

Glad you sorted it out!

As a minor note, copying and pasting text works a lot better than screen shots. It allows others who want to help to copy some part of your text and edit it easily to improve it without having to retype all of it by hand. It also works better on different resolution / size screens.

1 Like

Thanks for the tip Ben! :slight_smile:
I’ll update the solution with text