Kaziu
Posted on Nov 16
Edited on Nov 16
What happens
dependent: :destroy (so-called cascade delete) is handy: delete the parent record, and its child records go with it.
But if the children have callbacks , those callbacks fire on every single delete.
class Author < ApplicationRecord has_many :books , dependent : :destroy end
class Book < ApplicationRecord belongs_to :author , touch : true # deleting it updates the parent's updated_at (a "touch") after_destroy :reindex_search # reindexes Elasticsearch on every single delete (synchronous, heavy) end
Enter fullscreen mode
Exit fullscreen mode
When you call author.destroy β¦
destroy 1 Author ββ if there are 1000 books, destroy them one by one (cascade) ββ each time, touch the parent, and after_destroy runs an Elasticsearch update β 1000 times, one after another π±
Enter fullscreen mode
Exit fullscreen mode
You won't notice while the data is small, and then it suddenly times out with production-sized data.
Fix: delete only the heavy children first,β¦