Rails 3.2更新条件

时间:2012-06-17 04:43:53

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2

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

2 个答案:

答案 0 :(得分: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)})

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

答案 1 :(得分: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

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