2012-05-15 14 views
20

Ho un modello di attività associato a un modello di progetto tramite has_many through e ho bisogno di manipolare i dati prima di eliminare/inserire tramite l'associazione.Come utilizzare i callback in has_many attraverso l'associazione?

Poiché "Automatic deletion of join models is direct, no destroy callbacks are triggered." non posso utilizzare callback per questo.

In Attività ho bisogno di tutti i project_ids per calcolare un valore per Progetto dopo che l'attività è stata salvata. Come posso disabilitare cancellare o modificare delete to destroy su has_many attraverso l'associazione? Qual è la migliore pratica per questo problema?

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 

risposta

45

Sembra come devo usare associations callbacksbefore_add, after_add, before_remove o 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 
1

Questo è quello che ho fatto

nel modello:

class Body < ActiveRecord::Base 
    has_many :hands, dependent: destroy 
    has_many :fingers, through: :hands, after_remove: :touch_self 
end 

nel mio Cartella Lib:

module ActiveRecord 
    class Base 
    private 
    def touch_self(obj) 
     obj.touch && self.touch 
    end 
    end 
end 
Problemi correlati