有没有办法在保存时跳过更新与:touch关联的关联?
建立:
class School < ActiveRecord::Base has_many :students end class Student < ActiveRecord::Base belongs_to :school,touch: true end
我希望能够执行以下操作,跳过触摸.
@school = School.create @student = Student.create(school_id: @school.id) @student.name = "Trevor" @student.save # Can I do this without touching the @school record?
你能做这个吗?像@ student.save(skip_touch:true)之类的东西会很棒,但我还没有找到类似的东西.
我不想使用像update_column这样的东西,因为我不想跳过AR回调.
解决方法
避免直接猴子修补的一个选项是覆盖与a:touch属性建立关系时创建的方法.
鉴于OP的设置:
class Student < ActiveRecord::Base belongs_to :school,touch: true attr_accessor :skip_touch def belongs_to_touch_after_save_or_destroy_for_school super unless skip_touch end after_commit :reset_skip_touch def reset_skip_touch skip_touch = false end end @student.skip_touch = true @student.save # touch will be skipped for this save
这显然是非常hacky,取决于AR中真正具体的内部实现细节.