【问题标题】:How to prevent multiple queries when updating a record?更新记录时如何防止多次查询?
【发布时间】:2019-06-27 17:43:00
【问题描述】:

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

我认为额外的查询是为了检查关系是否仍然有效。但是当批量更新所有客户时,它非常慢。如何防止这些额外的查询?

【问题讨论】:

  • 尝试在你的模型中添加belongs_to :country, optional: true
  • 请在此处查看stackoverflow.com/questions/16699877/rails-optional-belongs-to,但这将使belongs_to关联在所有情况下都是可选的。
  • @AbhishekAravindan。谢谢,但它不应该是可选的。我正在寻找数据库只是试图更新/创建记录的东西。如果不能,那么我还是会收到错误消息。

标签: ruby-on-rails


【解决方案1】:

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

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

阅读更多关于update_attribute 和其他好方法的信息

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

  • 跳过验证。

  • 回调被调用。

  • updated_at/updated_on 列更新,如果该列是 可用。

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

【讨论】:

【解决方案2】:

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

试试

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

【讨论】:

    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多