0

With where we can do Item.where('stock_amount > ?', 0).

Question: Is there a way to write in ActiveRecord that will produce the following SQL?

UPDATE items SET stock_amount = stock_amount - 10 where id = 1;

I have tried

Item.update(1, {stock_amount: ['stock_amount - ?', 10]}

and it runs but does not produce the SQL I want.

I know I can achieve the same result with more lines like

item = Item.find(1)
item.stock_amount = item.stock_amount - 10
item.save

and using exec_update

ActiveRecord::Base.connection.exec_update('UPDATE items SET stock_amount = stock_amount - $1 WHERE id = $2', 'sql', [[nil, 10],[nil, 1]])

This post is the closest I get.

Tun
  • 1,345
  • 13
  • 34

1 Answers1

3
Item.where(id: 1).update_all(["stock_amount = stock_amount - ?", 10])

should produce:

UPDATE "items" SET stock_amount = stock_amount - 10 WHERE "items"."id" = $1  [["id", 1]]
Marcin Kołodziej
  • 5,253
  • 1
  • 10
  • 17
  • With Rails 5.1.6, I get little bit different SQL that achieve the same result. `UPDATE "items" SET stock_amount = stock_amount - 10 WHERE "items"."id" IN (SELECT "items"."id" FROM "items" WHERE "items"."id" = $1 ORDER BY "items"."name" ASC) [["id", 1]]` – Tun Nov 13 '18 at 20:14