开发者

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.开发者_如何学Go 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜