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:
:restrictprevents deletion of a referenced row (i.e. if you try to delete auserin the example above, an error will be raised if there are anyrevisionsassociated with that user):nullifywill set to null (i.e. if you delete auser, anyrevisionsassociated with that user will have theircreated_by_idset tonull):cascadewill cascade the deletion (i.e. if you delete auser, anyrevisionsassociated 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!