假设我的用户1-n使用UserNotification
问题是,我不知道为什么每次我尝试保存UserNotification时,rails都会自动选择该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用户模型很简单: belongs_to : UserNotification
我已经阅读了更新源代码,但仍然没有任何线索
有什么想法吗?
发布于 2018-11-10 04:02:45
问题是,在默认情况下,Rails5 make属于required。然后,每次更新记录时,它都会加载关联以验证其存在。您可以做的(我不知道这有多干净,但在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
https://stackoverflow.com/questions/46700161
复制相似问题