[Proposal] ActiveRecord update_each method (with callbacks)

For deleting records in an ActiveRecord collection, we have:

delete_all (bulk destroy with no callbacks) and it’s companion…

destroy_all (destroy each with callbacks)

Having two distinct methods for this is valuable because you have two clear options for deleting records from a collection.

However, this isn’t true for collection updates. We only have:

update_all (bulk update without callback)

update_all is missing it’s companion (maybe update_each) that updates each with callbacks.

Adding an update_each method would be a great natural companion for update_all, and give developers two clear options when updating a collection. It’s a small change, but I think it provides a better developer experience.

Thanks for considering this proposal!

Something like this?

https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-update

Rafael França Rails Core Team Member

1 Like

Wow! thanks Rafael, I had no idea you could do update on a collection.

What is the oldest version of Rails where this is possible?

5.0

Rafael França Rails Core Team Member

Makes me think that maybe ActiveRecord::Persistence::ClassMethods#update could have some sort of update_each alias to improve the discovery of this feature in the API, and for a slightly more intention-revealing name.

But maybe it’s just me. I used to glaze over that method in search results or when reading business code (which bit me a few times!), thinking it was about updating one record.

1 Like