ruby-on-rails – 跳过:保存ActiveRecord对象时触摸关联

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 跳过:保存ActiveRecord对象时触摸关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在保存时跳过更新与:touch关联的关联?

建立:

  1. class School < ActiveRecord::Base
  2. has_many :students
  3. end
  4.  
  5. class Student < ActiveRecord::Base
  6. belongs_to :school,touch: true
  7. end

我希望能够执行以下操作,跳过触摸.

  1. @school = School.create
  2. @student = Student.create(school_id: @school.id)
  3. @student.name = "Trevor"
  4. @student.save # Can I do this without touching the @school record?

你能做这个吗?像@ student.save(skip_touch:true)之类的东西会很棒,但我还没有找到类似的东西.

我不想使用像update_column这样的东西,因为我不想跳过AR回调.

解决方法

避免直接猴子修补的一个选项是覆盖与a:touch属性建立关系时创建的方法.

鉴于OP的设置:

  1. class Student < ActiveRecord::Base
  2. belongs_to :school,touch: true
  3.  
  4. attr_accessor :skip_touch
  5.  
  6. def belongs_to_touch_after_save_or_destroy_for_school
  7. super unless skip_touch
  8. end
  9.  
  10. after_commit :reset_skip_touch
  11.  
  12. def reset_skip_touch
  13. skip_touch = false
  14. end
  15. end
  16.  
  17. @student.skip_touch = true
  18. @student.save # touch will be skipped for this save

这显然是非常hacky,取决于AR中真正具体的内部实现细节.

猜你在找的Ruby相关文章