Rails 6 adds delete_by and destroy_by methods.


Rails has provided methods like find_by, find_or_initialize_by, and find_or_create_by to fetch, initialize, and create record respectivley, based on the passed conditions.

Similar method to delete or destroy records was missing in Rails.

As per this issue, Rails 6 has introduced two methods delete_by and destroy_by to ActiveRecord::Relation, which deletes or destroys all the records that match the passed conditions.

Before Rails 6:

Deleting or destroying records was executed as shown below:

User.where(is_active: false).delete_all
User.where(is_active: false).destroy_all

In Rails 6:

Rails 6 now provides convenience methods to achieve the same. The above examples can now be achieved similary like:

User.delete_by(is_active: false)
User.destroy_by(is_active: false)

The PR for this issue can be referred here.