BatchEnumerator#destroy_all To Return The Total Number Of Destroyed Records

The BatchEnumerator in Rails is a utility that allows processing large sets of records in smaller, more manageable batches.

This approach helps to avoid loading large datasets into memory all at once, which can be inefficient and slow.

The in_batches method provides a way to iterate over records in batches, applying actions to each batch sequentially.

The recent PR in Rails brings a significant improvement to the BatchEnumerator#destroy_all method.

Previously, this method returned nil after destroying records in batches, providing no feedback on the number of affected rows.

From Rails version 7.2, it will now return the total number of destroyed records.


Prior to the implementation of this feature, the method returned nil and to implement custom logic based on the affected rows, an additional query was required to count the records before deletion.

Let’s take an example to understand the behavior better

# Query for the count before deletion
record_count = User.where(active: false).count

User.where(active: false).in_batches.destroy_all

# Output: nil 


With the new change, we will now get total number of destroyed records in output and an additional query to count destroyed record will not be needed and it can also help in verifying that the expected number of records were affected.

destroyed_count = User.where(active: false).in_batches.destroy_all

# Output: 4

To know more about this feature, please refer to this PR

Need help on your Ruby on Rails or React project?

Join Our Newsletter