Reputation: 128
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
Reputation: 1401
User.find(123).increment(:views)
see http://apidock.com/rails/ActiveRecord/Base/increment http://apidock.com/rails/ActiveRecord/Base/increment!
Upvotes: -2
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
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
Reputation: 121010
User.connection.execute(%|
UPDATE users SET views = views + 1 WHERE id = 123
|)
Upvotes: 2