返回空数据时如何处理update_all

时间:2019-06-10 06:20:04

标签: ruby-on-rails

我正在使用update all更新一些数据库详细信息。当返回的数据为空时,更新全部失败ActiveRecord :: StatementInvalid:Mysql2 :: Error:未知列

例如,我知道可以解决此问题,但这看起来像是多余的使用,因为在我的代码库中,我做了如下更改

Product.where(local_product: true).update_all(tax: 0) if Product.where(local_product: true).present?

我希望update_all是否已自行处理,还是有其他方法?

2 个答案:

答案 0 :(得分:1)

只需一行即可完成,您无需检查是否有任何记录。

Product.where(local_product: true).update_all(tax: 0)将生成下一个sql查询:

UPDATE "products" SET "tax" = true WHERE "products"."local_product" = true

数据库为您过滤记录,您无需检查两次,如果没有要更新的数据,它将无济于事。

答案 1 :(得分:0)

尝试此操作以避免重复

@products = Product.where(local_product: true)
@products.update_all(tax: 0) if @products.present?