# Improve(?) has\_many :dependent =\> :destroy before destroy callback

**URL:** <https://www.ruby-forum.com/t/improve-has-many-dependent-destroy-before-destroy-callback/159371>\
**Category:** Rails\
**Created:** [February 3, 2009, 10:40pm UTC](https://www.ruby-forum.com/t/improve-has-many-dependent-destroy-before-destroy-callback/159371 "2009-02-03T22:40:38Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![seaquest](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/2bfe46/32.png) [@seaquest](https://www.ruby-forum.com/u/seaquest)\
**Post date:** [February 3, 2009, 10:40pm UTC](https://www.ruby-forum.com/t/improve-has-many-dependent-destroy-before-destroy-callback/159371/1 "2009-02-03T22:40:38Z")

</div>

Hi,  
I tried to submit this via lighthouse, but after third POST failure  
(mail also failed) I thought maybe someone here will be interested and  
forward this further.

In my application I have dependent models and I wanted to use  
before\_destroy callback to “validate” if dependent item could be  
destroyed:

@@@  
class Squad \< ActiveRecord::Base  
has\_many :trolls, :dependent =\> :destroy  
end

class Troll \< ActiveRecord::Base  
belongs\_to :squad  
before\_destroy :destroy\_cb

def destroy\_cb

# I am indestructible!

false  
end  
end  
@@@

Trying to destroy troll fails as expected, but when I destroy Squad,  
it is disbanded but members are still alive, go berserk and trash my  
database (foreign key points to invalid - removed - squad).  
When I command “Squad.first.destroy” I expect failure because my  
minions are indestructible - dependent-destroy should fail.

I propose following change: try to destroy all dependent items - as it  
is done now - then: if any dependent destroy operation failed, return  
failure and do not progress further.

(patch inline)  
— activerecord-2.2.2/lib/active\_record/associations.rb.orig  
2009-02-03 17:29:13.000000000 +0100  
+++ activerecord-2.2.2/lib/active\_record/associations.rb 2009-02-03  
17:30:49.000000000 +0100  
@@ -1452,7 +1452,7 @@  
when :destroy  
method\_name = “has\_many\_dependent\_destroy\_for\_#  
{reflection.name}”.to\_sym  
define\_method(method\_name) do

- 

```
             send(reflection.name).each { |o| o.destroy }

```

- 

```
             send(reflection.name).map { |o| o.destroy }.all?
           end
           before_destroy method_name
         when :delete_all
```
