Bulk Delete Records in Rails with `delete_by`
I'm sure you're familiar with the Active Record method delete_all
. But I recently learned of another method that can used to shorthand this method-call on a where
statement.
You see - delete_by(...)
is the shorthand for Model.where(...).delete_all
Model.where(foo: true, bar: false).delete_all
# vs.
Model.delete_by(foo: true, bar: false)
Similarly to delete_all
, you will need to be careful with delete_by
as it creates a single delete statement for the database and callbacks are not called.
Bonus round -> destroy_by
is a similar shorthand for Model.where(...).destroy
https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_by
Tweet