[Proposal] Adding `#increment_all` to `ActiveRecord::Relation`

Say you want to update a numeric column on a subset of records. update_all is fine:

Player.active.update_all("score = score + 10")

But using update_all with user input is very unsafe:

Player.active.update_all("score = score + #{params[:extra]}")

A safe way to do it is to use update_counters:

Player.active.update_counters(score: params[:extra])

But the naming of that method is a bit weird. We’re not updating these columns, we’re incrementing them. Also, these columns don’t need to be counters, they can be any number column.

I propose we add increment_all and decrement_all methods, as counterparts to the ActiveRecord instance increment and decrement. Then we could use:

Player.active.increment_all(:score, 10)

which is immediately clear.

1 Like

Pull request opened here: Add ActiveRecord::Relation#increment_all and decrement_all by shnikola · Pull Request #46524 · rails/rails · GitHub