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).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With