some help with deleting from the objects with dependencies

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

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.

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