本文介绍了跳绳:保存一个ActiveRecord对象时触摸协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为更新协会与:保存时触摸协会

Is there a way to skip updating associations with a :touch association when saving?

设置:

class School < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :school, touch: true
end

我希望能够做这样的事情,其中​​触摸跳过以下。

I would like to be able to do something like the following where the touch is skipped.

@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:真)将是非常美妙的,但我还没有发现类似的事情

Can you do this? Something like @student.save(skip_touch: true) would be fantastic but I haven't found anything like that.

我不希望使用类似 update_column ,因为我不想跳过AR回调。

I don't want to use something like update_column because I don't want to skip the AR callbacks.

推荐答案

一个选项,避免了直接猴子补丁是当你有一个关系来覆盖被创建的方法:触摸属性。

One option that avoids directly monkey patching is to override the method that gets created when you have a relation with a :touch attribute.

由于从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

这显然是pretty的哈克,并取决于真正具体的内部实现细节的AR。

This is obviously pretty hacky and depends on really specific internal implementation details in AR.

这篇关于跳绳:保存一个ActiveRecord对象时触摸协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 09:19