---
title: "Rails 6 delete_by, destroy_by ActiveRecord::Relation"
description:
  "In Rails 6, ActiveRecord::Relation has two new methods `delete_by` and
  `destroy_by`."
canonical_url: "https://www.bigbinary.com/blog/rails-6-adds-activerecord-relation-delete_by-and-activerecord-relation-destroy_by"
markdown_url: "https://www.bigbinary.com/blog/rails-6-adds-activerecord-relation-delete_by-and-activerecord-relation-destroy_by.md"
---

# Rails 6 delete_by, destroy_by ActiveRecord::Relation

In Rails 6, ActiveRecord::Relation has two new methods `delete_by` and
`destroy_by`.

- Author: Abhay Nikam
- Published: March 13, 2019
- Categories: Rails 6, Rails

As described by DHH in [the issue](https://github.com/rails/rails/issues/35304),
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.

```ruby

# Example to destroy all authors matching the given condition

Author.find_by(email: "abhay@example.com").destroy
Author.where(email: "abhay@example.com", rating: 4).destroy_all

# Example to delete all authors matching the given condition

Author.find_by(email: "abhay@example.com").delete
Author.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.

```ruby

# Example to destroy all authors matching the given condition using destroy_by

Author.destroy_by(email: "abhay@example.com")
Author.destroy_by(email: "abhay@example.com", rating: 4)

# Example to destroy all authors matching the given condition using delete_by

Author.delete_by(email: "abhay@example.com")
Author.delete_by(email: "abhay@example.com", rating: 4)
```

Check out the [pull request](https://github.com/rails/rails/pull/35316) for more
details on this.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-adds-activerecord-relation-delete_by-and-activerecord-relation-destroy_by)
