我有一个 rails 模型,我想通过计算该属性的当前值加上我作为参数发送的值来更新属性。以下将更新记录并覆盖属性的现有值
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
我想要更像这样的东西,但下面的语法不起作用。
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
编辑
与以下答案非常接近,但这是 sql 在后台运行的内容
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
代替
UPDATE `products`
SET `qty_on_hand` = 165, `qty_received` = 165
WHERE `products`.`client_id` = 1 AND `products`.`product_code` = '88-89c'