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.