BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 6 delete_by, destroy_by ActiveRecord::Relation

This blog is part of our Rails 6 series.

Rails 6.0 was recently released.

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.

1
2# Example to destroy all authors matching the given condition
3
4Author.find_by(email: "abhay@example.com").destroy
5Author.where(email: "abhay@example.com", rating: 4).destroy_all
6
7# Example to delete all authors matching the given condition
8
9Author.find_by(email: "abhay@example.com").delete
10Author.where(email: "abhay@example.com", 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.

1
2# Example to destroy all authors matching the given condition using destroy_by
3
4Author.destroy_by(email: "abhay@example.com")
5Author.destroy_by(email: "abhay@example.com", rating: 4)
6
7# Example to destroy all authors matching the given condition using delete_by
8
9Author.delete_by(email: "abhay@example.com")
10Author.delete_by(email: "abhay@example.com", rating: 4)

Check out the pull request for more details on this.

Abhay Nikam in Rails 6
March 13, 2019
Share

Subscribe to our newsletter