【发布时间】:2017-10-12 01:51:13
【问题描述】:
假设我有带有 UserNotification 的用户 1-n
问题是我不知道为什么每次我尝试保存 UserNotification 时,rails auto SELECT 那个 UserNotification 的用户触发了 n + 1 个问题
例如
UserNotification.where(id: [1,2,3]).update(updated_at: Time.current)
会生成这些SQL
UserNotification Load (0.4ms) SELECT `user_notifications`.* FROM `user_notifications` WHERE `user_notifications`.`id` IN (1, 2, 3)
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` IN (3, 1)
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 4
UserNotification 模型很简单 belongs_to :user
我已经阅读了更新源代码,但仍然没有头绪
有什么想法吗?
【问题讨论】:
标签: ruby-on-rails associations eager-loading