:dependent => :destroy and before_destroy

I have a problem with one of my models. The parent object has 2
polymorphic relationships both specifying :dependent => :destroy.
This all works fine until you attempt to delete the parent and the
parent’s before_destroy callback returns false. When the parent’s
before_destroy callback returns false, the parent is not deleted, but
the transaction is still committed so all of the objects from the
polymorphic relationships are destroyed. This is obviously not
desirable. I have verified that the call back is returning false. Is
there something I am missing or is this just normal. I can remove the
:dependent => :destroy and place the relevant code in my
before_destroy callback, but this seems to defeat the purpose of
:dependent and would get really messy on objects with many dependencies.

Here is the abbreviated code in question:


class Location < AbstractBase

has_one :address, :as => :addressed, :dependent => :destroy

has_one :contact, :as => :contactable, :dependent => :destroy

before_destroy :any_dependent_assets?


class AbstractBase < ActiveRecord::Base

You can run this in a transaction block:
@parent = Parent.find(params[:id])
Parent.transaction do

if @parent.destroy raises any exception the entire transaction will be rolled back and none of the children will be deleted.

Hey Ryan, thank for the suggestion but that won’t help as the destroy
is already wrapped in a transaction and the children are still deleted.
I can get things to work if I raise an exception in the parent’s before
filter and catch it in a begin / rescue / end block in the controller.
I guess what I really want to know is why would :dependent children be
destroyed if the parent’s before_destroy filter returns false? Seems to
me that is something is “dependent” than it should be just that. It
would be deleted only if the parent can be. I was expecting to see the
transaction rolled back when the parent’s before_destroy callback
returned false


Ryan Bigg wrote:

Ok, thats what I ended up with. Thanks again.

Ryan Bigg wrote: