The difference between on_delete: :restrict, :nullify, and :cascade

I was working on a Rails project today and came across this:

add_foreign_key "revisions", "users", column: "created_by_id", on_delete: :restrict

I knew what a foreign key was, but I didn’t know the impact of the on_delete callback. Looking around the codebase, other options were used too: :nullify and :cascade. And several searches online didn’t help to explain what any of these actually did.

A colleague pointed me in the direction of the PostgreSQL docs, which explained it for me:

  • :restrict prevents deletion of a referenced row (i.e. if you try to delete a user in the example above, an error will be raised if there are any revisions associated with that user)
  • :nullify will set to null (i.e. if you delete a user, any revisions associated with that user will have their created_by_id set to null)
  • :cascade will cascade the deletion (i.e. if you delete a user, any revisions associated with that user will be deleted too)

Hopefully this post will save another developer from fruitlessly Googling things. Let me know in the comments if this post helped you!

Loading...