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

Add ActiveRecord::Relation#increment_all and decrement_all #46524

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

shnikola
Copy link

Motivation / Background

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.

Detail

This pull request adds increment_all and decrement_all methods, corresponding to the ActiveRecord instance increment and decrement. This allows us to write:

Player.active.increment_all(:score, 10)

the result of which is immediately clear.

@shnikola shnikola changed the title Added ActiveRecord::Relation#increment_all and decrement_all Add ActiveRecord::Relation#increment_all and decrement_all Nov 18, 2022
@shnikola shnikola force-pushed the increment_all branch 4 times, most recently from ce3c913 to 4ba6fe8 Compare November 18, 2022 23:56
Previous way to increment a number column on multiple records was
using confusingly named update_counters. This adds Relation methods
corresponding to the ActiveRecord::Persistence#increment and decrement.

    Player.active.increment_all(:score, 10)
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

1 participant