0

我有一个 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'
4

2 回答 2

3

我相信这将基于文档 http://apidock.com/rails/ActiveRecord/Relation/update_all

Product.update_all(['qty_on_hand = qty_on_hand + ? , qty_received = qty_received + ?', qty_received, qty_received],
                    {:client_id => client_id, :product_code => product_code)})

请注意,这将在数据库中进行添加操作。

于 2012-06-17T05:08:27.410 回答
0

由于您正在更新所有并且手头的数量可能会发生变化,因此您应该循环查看 where 子句的结果:

def self.mark_receipt(qty_received,client_id,product_code)
  Product.where(:client_id => client_id, :product_code => product_code).each do |p|
    p.update_attributes(:qty_on_hand=> p.qty_on_hand + qty_received, :qty_received => p.qty_received + qty_received)
  end
end

我没有对此进行测试,但这应该为您指明正确的方向。

于 2012-06-17T04:52:10.463 回答