【问题标题】:Rails belongs_to triggered when call save调用 save 时触发 Rails belongs_to
【发布时间】: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


    【解决方案1】:

    问题是Rails 5 使默认情况下属于必需的。然后每次更新记录时,它都会加载关联以验证其存在。你可以做什么(我不知道这有多干净,但在 Rails 修复它之前我想这很好),是添加一个自定义验证来验证属于存在,以便它只在创建或更改关联记录时运行。

    belongs_to :my_association, optional: true
    validate :my_association, presence: true, if: :needs_validate_my_association_presence?
    
    def needs_validate_my_association_presence?
       new_record? || my_association_id_changed?
    end
    

    在您的情况下,my_association 将是 user

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-28
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多