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 foreign_key_constraint/3 on your changeset with the constraint :name as an option.
def delete(conn, %{"id" => post_id}) do
Repo.get!(Post, post_id) |> Repo.delete!
conn
|> put_flash(:info, "Post Deleted")
|> redirect(to: Routes.post_path(conn, :index))
end
You’ll need to use a Changeset to delete the record.
The Changeset.change/2 function can be used to wrap an existing struct in a Changeset.
Post
|> Repo.get!(post_id)
|> Changeset.change()
|> Changeset.foreign_key_constraint(:id, name: "comments_post_id_fkey", message: "can't be deleted, it is still in use")
|> Repo.delete
Here’s the output I get in an iex session:
Artist
|> Repo.get(1)
|> Changeset.change()
|> Changeset.foreign_key_constraint(:artist_id, name: "FK_AlbumArtistId", message: "can't be deleted, it is still in use")
|> Repo.delete()
[debug] QUERY OK source="Artist" db=2.3ms idle=55.4ms
SELECT A0."ArtistId", A0."Name" FROM "Artist" AS A0 WHERE (A0."ArtistId" = $1) [1]
[debug] QUERY ERROR db=2.0ms idle=58.0ms
DELETE FROM "Artist" WHERE "ArtistId" = $1 [1]
{:error,
#Ecto.Changeset<
action: :delete,
changes: %{},
errors: [
artist_id: {"is being used by another table",
[constraint: :foreign, constraint_name: "FK_AlbumArtistId"]}
],
data: #Artist<>,
valid?: false
>}