1

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.

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

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]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.