跳过:保存ActiveRecord对象时触摸关联

有没有办法在保存时跳过更新与: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中真正具体的内部实现细节。

从Rails v4.1.0.beta1开始,正确的方法是:

 @school = School.create @student = Student.create(school_id: @school.id) ActiveRecord::Base.no_touching do @student.name = "Trevor" @student.save end 

很不幸的是,不行。 save不提供此类选项。

解决这个问题的方法是使用另一个时间戳属性,其function类似于updated_at但与updated_at不同,它仅在某些情况下根据您的喜好进行更新。