Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mass increment field by 1

I have a query update deals set count = count + 1. In Rails, when I do this using ActiveRecord, I can think of

Deal.all.each { |deal| deal.update_attribute(:count => (deal.count + 1))}

and this take a lot more SQL queries instead of one query. Is there a better way to do this in Rails (not using the SQL query directly in the Rails app).

like image 519
rubyprince Avatar asked Feb 11 '11 09:02

rubyprince


2 Answers

Deal.update_all("count = count + 1")

outputs

UPDATE "deals" SET count = count + 1

And with a conditional:

Deal.where(order_id: 2).update_all("count = count + 1")

outputs

UPDATE "deals" SET count = count + 1 WHERE "deals"."order_id" = 2
like image 157
Evan Avatar answered Oct 13 '22 00:10

Evan


Using ActiveRelation update_all Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks.

http://apidock.com/rails/ActiveRecord/Base/update_all/class

like image 29
Syed Aslam Avatar answered Oct 12 '22 23:10

Syed Aslam