如何通过关联在has_many中使用回调?

ton*_*all 23 ruby-on-rails callback has-many-through ruby-on-rails-3

我有一个通过has_many通过项目模型关联的任务模型,需要在通过关联删除/插入之前操作数据.

由于" 自动删除连接模型是直接的,因此不会触发销毁回调. "我无法使用回调.

在任务中,我需要所有project_ids在保存任务后计算Project的值.如何通过关联禁用删除或更改删除以销毁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
Run Code Online (Sandbox Code Playgroud)

ton*_*all 53

好像我必须使用协会回调 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   
Run Code Online (Sandbox Code Playgroud)