Topic: Question about :dependent => :delete_all on nested has_many associatio

Alright, I have three models as follows:

class Section < ActiveRecord::Base
  has_many :volumes, :dependent => :delete_all
end

class Volume < ActiveRecord::Base
  has_many :chapters, :dependent => :delete_all
  belongs_to :section
end

class Chapter < ActiveRecord::Base
  belongs_to :volume
end


I'd like for everything to cascading delete when I delete a section, however, if I have :dependent set to :delete_all, only the volumes associated with it will be destroyed and I will be left with orphaned chapter records. I have experimented with some things and if I set :dependent to :destroy for the Section model then everything gets destroyed properly except I have an extremely heavy before_destroy that I do not want to run.

Is there anyway I can have it work with :delete_all? or is there a way to check if I'm deleting all in my before_destroy so I can skip my clean up (that way I can just use :destroy on the Volume model)?

Thanks for the help.

Re: Question about :dependent => :delete_all on nested has_many associatio

So, anyone have any idea?

Re: Question about :dependent => :delete_all on nested has_many associatio

The delete_all just sends a delete SQL query which bypasses all callbacks. The ":dependent => :destroy" sets up its own before_destroy callback so that when the model is destroyed, it will call destroy on all other models (resulting in the other before_destroy callbacks being called).

AFAIK there is no way to exclude callbacks conditionally like this short of setting some instance variable before doing the cascade destroy and checking upon that.

However, the fact that you don't want a given before_destroy callback to be called in certain situations makes me think this shouldn't be in a callback. Perhaps you can extract this into its own method and call that before destroying the model in the times you want the code to be executed.

Hope that made sense.

Railscasts - Free Ruby on Rails Screencasts