Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto use callbacks in a has_many through association?

Tags:

I have a Task model associated to a Project model via has_many through and need to manipulate the data before delete/insert via the association.

Since "Automatic deletion of join models is direct, no destroy callbacks are triggered." i can not use callbacks for this.

In Task i need all project_ids to calculate a value for Project after Task is saved. How can i disable delete or change delete to destroy on has_many through association? What is best practise for this problem?

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 
like image 797
tonymarschall Avatar asked May 15 '12 09:05

tonymarschall


2 Answers

Seems like i have to use associations callbacks before_add, after_add, before_remove or 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    
like image 128
tonymarschall Avatar answered Oct 07 '22 15:10

tonymarschall


This is what I did

in the model:

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

in my Lib folder:

module ActiveRecord   class Base   private     def touch_self(obj)       obj.touch && self.touch     end   end end 
like image 44
Nicolai Avatar answered Oct 07 '22 16:10

Nicolai