如何通过关联在has_many中使用回调?
我有一个通过has_many通过项目模型关联的任务模型,需要在通过关联删除/插入之前操作数据。
由于“ 自动删除连接模型是直接的,因此不会触发销毁回调。 ”我无法使用回调。
在任务中,我需要所有project_ids在保存任务后计算项目的值。 如何通过关联禁用删除或更改删除以销毁has_many? 这个问题的最佳做法是什么?
class Task has_many :project_tasks has_many :projects, :through => :project_tasks class ProjectTask belongs_to :project belongs_to :task class Project has_many :project_tasks has_many :tasks, :through => :project_tasks
好像我必须使用关联回调 before_add
, after_add
, before_remove
或after_remove
class Task has_many :project_tasks has_many :projects, :through => :project_tasks, :before_remove => :my_before_remove, :after_remove => :my_after_remove protected def my_before_remove(obj) ... end def my_after_remove(obj) ... end end
这就是我所做的
在模型中:
class Body < ActiveRecord::Base has_many :hands, dependent: destroy has_many :fingers, through: :hands, after_remove: :touch_self end
在我的Lib文件夹中:
module ActiveRecord class Base private def touch_self(obj) obj.touch && self.touch end end end