Option on_delete: :delete_all raises error instead of deleting errors

Hey there! I’ve got 2 tables with a relationship of one-to-many, and when I try to delete a record from the parent table it raises an error instead of deleting the child records as well.

Here are my table migrations:

create table("user") do
      add(:username, :string, null: false)
      add(:email, :string, null: false)
      add(:password_hash, :string, null: false)
      timestamps()
end

create table("usersession") do
      add(:user_id, references(:user), null: false, on_delete: :delete_all)
      add(:session, :string, null: false)
      timestamps()
end

When trying to run something like Repo.delete(Repo.get!(User, 1)) it just throws a constraint error instead of deleting the record. It’s weird because it feels like this should work and delete all cascading records, right? What am I doing wrong?

Looks like the on_delete option is in the wrong place in the migration, it should be specified for the references/2 function: Ecto.Migration — Ecto SQL v3.8.1

As a general tip, I suggest looking at the actual structure of your database and seeing if it matches what you expect based on the migrations.

Thank you! Yeah, it was quite a dumb mistake on my part, but I don’t think I came across an example of it being used so I just went with this.