使用数学更新多行以添加到现有值

Update multiple rows using math to add to existing value

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

我目前有类似的东西。

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

我认为你必须删除 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_each here

如果对所有记录添加相同的值,可以使用如下:

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

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