I have a method which updates a count of dependent objects for a parent class whenever a dependent is created or destroyed. This generally works, but for some reason when a parent is deleted by a third class with :dependent => :destroy, I get a nil error for the parent object when the count method is called and thus nothing gets deleted. If I attempt to raise parent.inspect from the count method during this operation, it gets returned, so it clearly isn't nil. Any thoughts?
class DependentObject < ActiveRecord::Base
belongs_to :parent
belongs_to :third_object
after_destroy :count
def count
count = DependentObject.count(:all, :conditions => ['parent_id = ?', self.parent_id])
self.parent.count = count
self.parent.save
end
end
class Parent < ActiveRecord::Base
belongs_to :third_object
has_many :dependent_objects, :dependent => :delete_all
end
class ThirdObject
has_many :parents, :dependent => :destroy
has_many :dependent_objects, :dependent => :destroy
end
EDIT: The reason why I have :dependent => delete_all in the parent method was that I naively assumed that since :delete_all does not trigger :after_destroy and would only be called when a parent is destroyed, that it would avoid this problem. Looking at the development logs, this is indeed the case since it says 'DependentObject Delete all' for all the relevant objects before going through later and going back with 'DependentObject Destroy all' and encountering the nil error and initiating a rollback.