Some database engines support legit foreign key constraints: if someone tries to save a Child
with a parent_id
of 5, but there's no Parent
with id
5, then the database itself (not Rails) will reject the record if there's a foreign key constraint linking children.parent_id
and parents.id
.
A foreign key can also specify what happens if the parent is deleted: in MySQL, for example, we can delete or nullify the dependent records, like how Rails does with :dependent
, or even just straight-up reject the deletion and throw an error instead.
Since not all database engines offer this functionality, Rails offers to emulate it with :dependent
, and it's nice to have it on the software level so that dependent child records can fire their destroy
callbacks when the parent is deleted. Since the feature is engine-independent and therefore pretty much schema-independent, Rails doesn't handle the creation/deletion of foreign keys. That's where foreigner
comes in: if your engine supports foreign key constraints, and you want that extra confident in your data integrity, foreigner
can help with that.