Simon
Simon

Reputation: 128

ActiveRecord update_column: How to increase a record value depending on it's current value with just one query

The below hits database twice - how do I reduce it to single query?

@user = User.find(123)
@user.update_column(:views, @user.views + 1)

Something like this:

User.find(123).update_column(:views, self.views + 1)

Upvotes: 2

Views: 1897

Answers (4)

Stefan
Stefan

Reputation: 114248

Rails has a dedicated method increment_counter to increment a numeric field by one:

User.increment_counter(:views, 123)
# UPDATE `users` SET `views` = COALESCE(`views`, 0) + 1 WHERE `users`.`id` = 123

COALESCE(`views`, 0) ensures that it also works with NULL.

Upvotes: 6

Andrey Deineko
Andrey Deineko

Reputation: 52367

User.where(id: 123).update_all('views = views + 1')

It will produce the following query:

UPDATE users SET views = views + 1 WHERE users.id = 123

Upvotes: 9

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

User.connection.execute(%|
  UPDATE users SET views = views + 1 WHERE id = 123
|)

Upvotes: 2

Related Questions