active_record_doctor icon indicating copy to clipboard operation
active_record_doctor copied to clipboard

Check for `dependent: :destroy_async` and a foreign key

Open fatkodima opened this issue 2 years ago • 0 comments

Rails 6.1 introduced dependent: :destroy_async which allows to destroy associated records in the background. This is useful when the parent record has lots of associated records and destroying all of them in the same transaction can potentially take a lot of time and/or lead to long database locks.

From the documentation:

WARNING: Do not use this option if the association is backed by foreign key constraints in your database. The foreign key constraint actions will occur inside the same transaction that deletes its owner.

So one can create a foreign key with on_delete: :cascade and an association with dependent: :destroy_async and when destroying the parent record, all the child records will be deleted/nullified immediately in the same transaction. This can run unnoticed for some time and blow up production later.

fatkodima avatar Jul 15 '22 21:07 fatkodima