ruby-on-rails – 跳过:保存ActiveRecord对象时触摸关联
发布时间:2020-12-16 19:04:35 所属栏目:百科 来源:网络整理
导读:有没有办法在保存时跳过更新与:touch关联的关联? 建立: class School ActiveRecord::Base has_many :studentsendclass Student ActiveRecord::Base belongs_to :school,touch: trueend 我希望能够执行以下操作,跳过触摸. @school = School.create@student
有没有办法在保存时跳过更新与: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中真正具体的内部实现细节. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |