跳过:保存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回调

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

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

避免直接打猴式补丁的一个选项是覆盖当您与: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

这显然是相当粗糙的,并且依赖于真正具体的AR内部实现细节。

遗憾的是,没有。save不提供这样的选项。

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

最新更新