更新记录时如何防止多个查询?

时间:2019-06-27 09:08:33

标签: ruby-on-rails

我有一个customers表,上面有几个belong_to:客户属于一个国家,一个部门和一个类型。

更新客户时,我得到以下结果:

> Customer.first.update(notes: "Some extra notes")
  Customer Load (1.4ms)  SELECT  `customers`.* FROM `customers` ORDER BY `customers`.`id` ASC LIMIT 1
  Country Load (1.5ms)  SELECT  `countries`.* FROM `countries` WHERE `countries`.`id` = '26' LIMIT 1
  Sector Load (1.6ms)  SELECT  `sectors`.* FROM `sectors` WHERE `sectors`.`id` = 89 LIMIT 1
  Type Load (1.6ms)  SELECT  `types`.* FROM `types` WHERE `types`.`id` = 8 LIMIT 1
  Customer Update (0.3ms)  UPDATE `customers` SET `notes` = "Some extra notes", `updated_at` = '2019-06-27 08:52:56' WHERE `customers`.`id` = 1

我认为这些额外的查询可以检查关系是否仍然有效。但是,大规模更新所有客户时,这非常慢。如何防止这些多余的查询?

2 个答案:

答案 0 :(得分:1)

您可以改用update_attribute,因为它不会在模型上运行任何验证。

Customer.first.update_attribute(:notes, 'Some extra notes')

详细了解update_attribute和其他不错的方法

更新单个属性并保存记录。这对于现有记录上的布尔标志特别有用。另请注意

  • 验证已跳过。

  • 调用回调。

  • 如果
  • updated_at / updated_on列已更新 可用。

  • 更新该对象中所有脏的属性。

答案 1 :(得分:0)

如果您确实确定不需要,可以使用update_columns跳过回调。

尝试

Customer.first.update_columns(notes: "Some extra notes")