This blog is part of our Rails 6 series.
As described by DHH in the issue,
Rails has find_or_create_by, find_by and similar methods to create and find
the records matching the specified conditions. Rails was missing similar feature
for deleting/destroying the record(s).
Before Rails 6, deleting/destroying the record(s) which are matching the given condition was done as shown below.
# Example to destroy all authors matching the given condition
Author.find_by(email: "[email protected]").destroy
Author.where(email: "[email protected]", rating: 4).destroy_all
# Example to delete all authors matching the given condition
Author.find_by(email: "[email protected]").delete
Author.where(email: "[email protected]", rating: 4).delete_all
The above examples were missing the symmetry like find_or_create_by and
find_by methods.
In Rails 6, the new delete_by and destroy_by methods have been added as
ActiveRecord::Relation methods. ActiveRecord::Relation#delete_by is short-hand
for relation.where(conditions).delete_all. Similarly,
ActiveRecord::Relation#destroy_by is short-hand for
relation.where(conditions).destroy_all.
Here is how it can be used.
# Example to destroy all authors matching the given condition using destroy_by
Author.destroy_by(email: "[email protected]")
Author.destroy_by(email: "[email protected]", rating: 4)
# Example to destroy all authors matching the given condition using delete_by
Author.delete_by(email: "[email protected]")
Author.delete_by(email: "[email protected]", rating: 4)
Check out the pull request for more details on this.

Related blogs
- 01Rails 6 adds support to persist timezones of Active JobSeptember 1, 2020 · Chetan Gawai
- 02Rails 6 adds including & excluding method on EnumerablesAugust 18, 2020 · Akhil Gautam
- 03Rails 6 fixes after_commit callback invocation bugFebruary 25, 2020 · Amit Choudhary
- 04Rails 6 adds rails db:prepare to migrate or setup a databaseDecember 10, 2019 · Akhil Gautam