Handling foreign key constraint errors in an Ecto.Model

Pomodoro.cc
1 min readFeb 12, 2016

--

I stumbled upon a ConstraintError thrown by the Ecto.Repo saying:

(Ecto.ConstraintError) constraint error when attempting to insert model

It was thrown because I defined a foreign key constraint in my migration, but didn’t specify it in the model!

The solution is to use foreign_key_constraint/3 in the changeset of your model, to validate the foreign_keys, so that you can use the not-throwing functions of the repo (like insert/2 etc) to pattern-match against errors.

You need to be working with changesets when inserting into the repo, else the validation errors will propagate to the repo and throw an exception.

Like this:

def changeset(model, params \\ :empty) do
cast(model, params, @required_fields, @optional_fields)
|> foreign_key_constraint(:pomodoro_id)
|> foreign_key_constraint(:todo_id)
end

and pattern match against possible errors like this:

pomodoro_todo = PomodoroTodo.changeset(%PomodoroTodo{}, %{pomodoro_id: pomodoro_id, todo_id: todo_id})case insert pomodoro_todo do
{:ok, pomodoro_todo} ->
{:ok, pomodoro_todo}
{:error, changeset} ->
IO.inspect changeset
{:error, changeset}
end

--

--