【发布时间】: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