Alex Rivera | Logout

Rails: how to disable before_destroy callback when it's being destroyed because of the parent is being destroyed (:dependent => :destroy)

Asked 2012-01-25T09:45:35.920
23

I have two classes: Parent and Child with

Child:

belongs_to :parent

and

Parent

has_many :children, :dependent => :destroy

The problem is that I want to check that there is always at least one child present, so I have a before_destroy method in Child that abort the destroy if it is the only child belonging to its parent.

And, if I want to destroy the parent, it will call the before_destroy callback on every child, but when there is one child, it will abort the destroy, so the parent will never get destroyed.

How can I tell the child to call the before_destroy callback only if it's not being destroyed because of its parent?

Thanks!

Edit
Report

1 Answer

10
has_many :childs, :dependent => :delete_all

This will delete all the children without running any hooks.

You can find the documentation at: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

answered 2012-01-25T14:38:20.290

Your Answer