【问题标题】:Update multiple rows using math to add to existing value使用数学更新多行以添加到现有值
【发布时间】:2015-09-27 22:18:45
【问题描述】:

我正在尝试更新多行。有些行可能已经有一个值。因此,如果该行中的值为 2,并且我想用额外的 4 更新它以使总数为 6。如何在不查询每一行的当前值的情况下做到这一点?还是我必须这样做?

我目前有类似的东西。

item_match = Item.where("id IN (?)", item_match_ids).to_a
item_match.update_all(quantity: quantity)

【问题讨论】:

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


    【解决方案1】:

    如果向所有记录添加相同的值,您可以使用以下内容:

    item_match.update_all("quantity = quantity + #{ quantity }")
    

    这比单独更新记录要快得多。为了安全起见,您应该将quantity 列设为非空并设置默认值。如果是用户提供的,请务必清理 SQL 的 quantity 值。

    【讨论】:

      【解决方案2】:

      我认为你必须删除to_a,这样离开:

      Item.where(id: [id1, id2, ...]).update_all(quantity: quantity)
      

      但是,如果您想为每条记录添加数量,您需要使用 find each:

      Item.where(id: [id1, id2, ...]).find_each do |item|
        item.update(quantity: item.quantity + quantity)
      end
      

      你会发现更多find_eachhere

      【讨论】:

        猜你喜欢
        • 2012-09-26
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        • 2011-12-20
        • 2011-11-22
        相关资源
        最近更新 更多