# Some help with deleting from the objects with dependencies

**URL:** <https://www.ruby-forum.com/t/some-help-with-deleting-from-the-objects-with-dependencies/133784>\
**Category:** Rails\
**Created:** [April 3, 2008, 4:05pm UTC](https://www.ruby-forum.com/t/some-help-with-deleting-from-the-objects-with-dependencies/133784 "2008-04-03T16:05:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tonypm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/a587f6/32.png) [@tonypm](https://www.ruby-forum.com/u/tonypm)\
**Post date:** [April 3, 2008, 4:05pm UTC](https://www.ruby-forum.com/t/some-help-with-deleting-from-the-objects-with-dependencies/133784/1 "2008-04-03T16:05:42Z")

</div>

Would welcome some advice on this:

I have customers, orders and batches.

Customer has many Orders  
Batch has many Orders

Now I want to do a batch delete, that will delete all orders in the  
batch and when the orders are deleted, I want to delete any customers  
that belong to the order provided they dont belong to any other  
orders.

I am thinking that :dependent=\>:delete\_all would seem ok for the  
orders, but I don’t know how to handle the customers. My current  
thinking is to let the customers become orphaned and then just clean  
them up by deleting all customers with 0 orders. But that feels a bit  
loose.

Thanks  
Tony

---

<div class="post-metadata">

**Author:** ![tonypm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/a587f6/32.png) [@tonypm](https://www.ruby-forum.com/u/tonypm)\
**Post date:** [April 3, 2008, 4:10pm UTC](https://www.ruby-forum.com/t/some-help-with-deleting-from-the-objects-with-dependencies/133784/2 "2008-04-03T16:10:28Z")

</div>

There’s likely a better way than this, but to start out I think I  
would first create an array of the id’s in customer.orders. Then  
delete the batch while cascade deleting the orders. After that  
completes successfully then delete the customers from the list you  
stored in the array [WHERE customers.id in (x, y, z)].

Also it would be best to do this in a single transaction so that it  
can be rolled back in case there are any errors.

Just a thought, but does this relationship make sense to your  
application:  
Customer has many Batches :dependent =\> :destroy  
Batch has many Orders :dependent =\> :destroy

I assume it doesn’t, but I wanted to mention it just in case it does.

---

<div class="post-metadata">

**Author:** ![tonypm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/a587f6/32.png) [@tonypm](https://www.ruby-forum.com/u/tonypm)\
**Post date:** [April 8, 2008, 8:49am UTC](https://www.ruby-forum.com/t/some-help-with-deleting-from-the-objects-with-dependencies/133784/3 "2008-04-08T08:49:26Z")

</div>

Thanks for the suggestion Robert.

For my purposes I did this in the end

In order.rb

def before\_destroy  
customer.destroy if customer.orders.count == 1  
end

seems to have achieved the desired result.

Tonypm
