I have a rails model where I want to update an attribute by calculating the current value of that attribute plus the value I’m sending as a parameter. The following will update the record and overwrite the existing value for the attribute
def self.mark_receipt(qty_received,client_id,product_code)
Product.where(:client_id => client_id, :product_code => product_code)
.update_all(:qty_on_hand => :qty_received,
:qty_received => qty_received)
end
I want something more like this, but the following syntax doesn’t work.
def self.mark_receipt(qty_received,client_id,product_code)
Product.where(:client_id => client_id, :product_code => product_code)
.update_all(:qty_on_hand => :qty_on_hand + qty_received,
:qty_received => :qty_received + qty_received)
end
EDIT
Getting really close with the below answer, but this is what sql is running in the background
Product Load (0.5ms) SELECT `products`.* FROM `products`
WHERE `products`.`client_id` = 1 AND `products`.`product_code` = '88-89c'
SQL (0.6ms) UPDATE `products`
SET `qty_on_hand` = 165, `qty_received` = 165
Instead of
UPDATE `products`
SET `qty_on_hand` = 165, `qty_received` = 165
WHERE `products`.`client_id` = 1 AND `products`.`product_code` = '88-89c'
I believe this would work based on docs
http://apidock.com/rails/ActiveRecord/Relation/update_all
Notice that this would make the add operation at the database.