Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change BatchEnumerator#destroy_all to return the total number of affected rows #51788

Merged

Conversation

fatkodima
Copy link
Member

Currently, ActiveRecord::Relation.destroy_all returns all the affected records, so users can implement some custom logic based on that without querying the database prior to the destroy_all call.

But, in_batches.destroy_all always returns nil, which is not very much useful. And in this case, to implement some custom logic based on the affected rows, we actually need to query the database prior to the operation.

This PR changes that method to always return the number of destroyed records.

@fatkodima fatkodima force-pushed the batch_enumerator-destroy_all-returns-rows-number branch from 5f7a63b to 211c6bd Compare May 13, 2024 07:36
#
# Person.where("age < 10").in_batches.destroy_all
#
# See Relation#destroy_all for details of how each batch is destroyed.
def destroy_all
each(&:destroy_all)
sum do |relation|
relation.destroy_all.size
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If what we want is the total number of rows "affected", we should count destroyed records, since destroy_all returns matched records whether a record is destroyed or not. ref #37782 (comment)

Suggested change
relation.destroy_all.size
relation.destroy_all.count(&:destroyed?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, thanks! Also updated the test case to account for this.

@fatkodima fatkodima force-pushed the batch_enumerator-destroy_all-returns-rows-number branch from 211c6bd to 94af7c1 Compare May 13, 2024 19:54
@kamipo kamipo merged commit 1b6b1a9 into rails:main May 14, 2024
1 of 3 checks passed
@fatkodima fatkodima deleted the batch_enumerator-destroy_all-returns-rows-number branch May 14, 2024 12:15
kamipo added a commit that referenced this pull request May 14, 2024
…-returns-rows-number

Change `BatchEnumerator#destroy_all` to return the total number of affected rows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants