rails/rails

dependent => :destroy deletes children before "before_destroy" is executed

jaylevitt opened this issue ยท 36 comments

Reposting #670 since the lighthouse importer auto-closed it, even though it was still open on lighthouse...

Problem: Upon destroying an ActiveRecord::Base object, the "before_destroy" method - which should trigger a transaction rollback if returning false - is only exceuted AFTER all child objects have been destroyed via ":dependent => :destroy".

However, this prevents before_destroy from seeing those same child objects, in case it needs them to determine whether the destruction should be successful.

Expected behaviour:

before_destroy should be called before any objects are destroyed, even child records. The before_destroy context should see the original state of the application as if destroy were never called. It should be executed within the destroy transaction, however, so that any changes it makes can be rolled back.

class Foo < AR::Base
  has_many :children, :dependent => :destroy
  has_many :grandchildren, :through => :children

  before_destroy :check
  def check
    # will always be true since all grandchildren have already been destroyed at this stage
    return self.grandchildren.still_there.empty?
  end
end

class Child < AR::Base
  has_many :grandchildren
  belongs_to :foo
end

class Grandchild < AR::Base
  belongs_to :child
  scope :still_there, :conditions => ...
end

Per discussion on #670, the problem is that :dependent => :destroy is in fact implemented as a before_destroy callback, and since callbacks are executed in the order they're defined, the :dependent callback is run before the :check callback. The solution seems to be either force the :dependent callback to run last, or make it its own callback.

me too facing the same problem.....

hey it is not a issue in rails... since previously we are doing everything in transaction for dependent destroy, but now in Rails 3.1.3 we are building the before_destroy method internally we need to rearrange the code.

so your code should be:

class Foo < AR::Base
before_destroy :check
has_many :children, :dependent => :destroy
has_many :grandchildren, :through => :children

def check
# will always be true since all grandchildren have already been destroyed at this stage
return self.grandchildren.still_there.empty?
end
end

class Child < AR::Base
has_many :grandchildren
belongs_to :foo
end

class Grandchild < AR::Base
belongs_to :child
named_scope :still_there, :conditions => ...
end

This will do the trick..... :)

@mitjain123: I respectfully disagree.. I think macros should try as hard as possible to act as declarative as they look.

@jaylevitt did you tried this?

here is the rails code which does that.

def configure_dependency
        if options[:dependent]
          unless options[:dependent].in?([:destroy, :delete_all, :nullify, :restrict])
            raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
                                 ":nullify or :restrict (#{options[:dependent].inspect})"
          end

          send("define_#{options[:dependent]}_dependency_method")
          model.before_destroy dependency_method_name
        end
      end

so this is creating a method: before_destroy :X_method

and if X_method is defined before any other before_destroy that will be executed.

may this makes you more clear.

@mitjain123: I'm saying class macros like before_destroy are declarative, and order shouldn't matter. I understand that it does matter because of the internal implementation, and I understand the workaround. I'm saying there shouldn't need to be a workaround.

the workaround, to move the before_destroy callback before the has_many, actually only works half way!!
It does not destroy the "parent", but it still destroy the children.

Maybe at least make this behaviour clear in the documentation?

This is a regression as before_destroy works fine in this manner in 3.0.10 !

Is this still an issue?

Just want to chime in that I got bitten by this. Can't they be moved to a different chain that's executed after user-defined before_destroys? It's not very obvious that dependent: :destroy calls before_destroy internally and that the order of its declaration matters.

Just bitten by this too. +1 to a less error-prone solution for this issue, independent of the macro definition order.

@pyrat are you sure it was working in 3.0.10? I just did a test and it's broken there too.

Just bitten by this too in Rails 3.2.3 +1 For a better solution, or at least indicate this in documentation.

Just bit me too. I agree that this should, at least, be in the documentation.

Same problem here with 3.2.2. Is there any workaround for observers?

We have also ran into this issue. If this is expected behaviour then it should be clearly highlighted in the documentation.

I've just pushed lifo/docrails#ecaf72877, which adds documentation for this behavior.

Changing this behavior might mess with existing apps, and so we'd need a migration path. Since it's not exactly a bug, and I've written documentation, I'm giving this a close. If someone would like to make them work in a more declarative fashion, please implement it and submit a pull request, or ping rails-core to see if it's even a good idea; changing this may subtly break a lot of apps.

Thanks!

Just got bitten by this too. It is definitely counter intuitive, especially if your models are defined in an acts_as module and you want your code to look like

class MyClass
  acts_as_foo    
  before_destroy :bar
end

@steveklabnik Seeing as how it subtly broke a lot of apps by changing to the way it is right now, I think "how do you think it should work" should be the criteria for deciding on the behaviour. I'll poke around in there and see if there's a way to do it that makes sense, and doesn't require us to document why this doesn't work the way you expect it to work anymore.

Biten by this too. I agree with @jaylevitt, this is a bug and not a "documentation problem". Declarations orders shouldn't matter.

@steveklabnik I feel like this should also be mentioned in the documentation for ActiveRecord::Observer

Right now, I don't think there is any way for before_destroy methods in observers to see whether or not the model-in-question had children.

Go ahead and send a pull request to rails/rails-observers , since Observers are no longer in Rails.

The but problem with this is issue is that it is not consistent, for example we are seeing the problem when running in POW but not in Webrick. I'm unsure if we're seeing it in production (Passenger + REE) but it seems that we are.

A number have people have referenced the order of the has_many and before_destroy but it doesn't seem to make any difference for us, only the hosting environment which is not comforting. We're going to look into it a little more in an empty Rails project and will report back.

Just bitten by this too. This should be mentioned in the documentation at least. Very frustrating!

r0qs commented

Is this still an issue?

Same

Same

Still having the same issue here too

Yeah, I just fixed it by swapping positions for before_destroy and dependent: :destroy. This fixed the problem.

Another approach (basically built for this):

(using the original example)

class Foo < AR::Base
  has_many :children, :dependent => :destroy
  has_many :grandchildren, :through => :children

  before_destroy :check, prepend: true

  def check
    # this will run before the dependent: destroy callback.
    return self.grandchildren.still_there.empty?
  end
end

prepend: true will cause the callback to run before the dependent destroy on the children.

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

@xinranxiao Here if you want to restrict to delete record need to throw exception to abort
throw(:abort) if you return false it'd not work as expected.

^that is only the case if using Rails 5 with ActiveSupport.halt_callback_chains_on_return_false = false set right?

i solved this problem by using a funny hack,
you just need to put the before_destroy line
before the association line
and it will run before_destroy before deleting the associations

I just got bit too, but by dependent: :nullify variation - the mechanism is the same thou. The solution makes sense :)
Thanks @xinranxiao for the prepend idea ๐Ÿ‘