2012-05-15 24 views
20

我有一個任務模型通過has_many關聯到項目模型,並且需要在通過關聯刪除/插入之前操作數據。如何通過關聯在has_many中使用回調?

由於「Automatic deletion of join models is direct, no destroy callbacks are triggered.」我不能使用回調。

在任務中,我需要所有project_id在保存任務後計算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 

回答

45

好像我不得不使用associations callbacksbefore_addafter_addbefore_removeafter_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 
1

這是我在模型中所做

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 
相關問題