Today I Learned

hashrocket A Hashrocket project

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

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.