Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jaylevitt opened this issue Oct 28, 2011 · 36 comments
Closed

Comments

@jaylevitt
Copy link
Contributor

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
@jaylevitt
Copy link
Contributor Author

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.

@ganeshkumar
Copy link
Contributor

me too facing the same problem.....

@mitijain123
Copy link
Contributor

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..... :)

@raghunadhd
Copy link
Contributor

Good one @mitijain123

@jaylevitt
Copy link
Contributor Author

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

@mitijain123
Copy link
Contributor

@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.

@jaylevitt
Copy link
Contributor Author

@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.

@aka47
Copy link
Contributor

aka47 commented Feb 1, 2012

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.

@tamaloa
Copy link

tamaloa commented Feb 2, 2012

Maybe at least make this behaviour clear in the documentation?

@pyrat
Copy link
Contributor

pyrat commented Feb 10, 2012

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

@isaacsanders
Copy link
Contributor

Is this still an issue?

@jaylevitt
Copy link
Contributor Author

@isaacsanders: yes.

@scomma
Copy link

scomma commented May 31, 2012

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.

@rogercampos
Copy link

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

@kliuless
Copy link

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

@hackhowtofaq
Copy link

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

@gstark
Copy link

gstark commented Aug 7, 2012

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

@aless
Copy link

aless commented Aug 30, 2012

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

@mtaylor
Copy link

mtaylor commented Sep 11, 2012

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

@steveklabnik
Copy link
Member

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!

@njakobsen
Copy link
Contributor

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.

@Silex
Copy link

Silex commented Jan 10, 2013

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

@earnold
Copy link
Contributor

earnold commented Mar 19, 2013

@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.

@steveklabnik
Copy link
Member

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

daviddavis pushed a commit to Katello/katello that referenced this issue Apr 23, 2013
Moving before_destroy callbacks because of rails/rails#3458
jlsherrill pushed a commit to jlsherrill/katello that referenced this issue Apr 23, 2013
daviddavis pushed a commit to Katello/katello that referenced this issue Apr 27, 2013
daviddavis pushed a commit to Katello/katello that referenced this issue Apr 27, 2013
Moving before_destroy callbacks because of rails/rails#3458
daviddavis pushed a commit to Katello/katello that referenced this issue Apr 30, 2013
@AnwarShah
Copy link

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

damianlegawiec added a commit to spark-solutions/spree that referenced this issue Jun 15, 2016
…Product/Variant

Previously : ensure_no_line_items  callback could stop deleting the
Product/Variant but associations (with dependent: :destroy) were
deleted whatsoever, as this is a rails bug (see
rails/rails#3458)
damianlegawiec added a commit to spark-solutions/spree that referenced this issue Jun 15, 2016
…Product/Variant

Previously : ensure_no_line_items  callback could stop deleting the
Product/Variant but associations (with dependent: :destroy) were
deleted whatsoever, as this is a rails bug (see
rails/rails#3458)
damianlegawiec added a commit to spark-solutions/spree that referenced this issue Jun 15, 2016
…Product/Variant

Previously : ensure_no_line_items  callback could stop deleting the
Product/Variant but associations (with dependent: :destroy) were
deleted whatsoever, as this is a rails bug (see
rails/rails#3458)
damianlegawiec added a commit to spark-solutions/spree that referenced this issue Jun 16, 2016
…Country

Previously :ensure_not_default  callback could stop deleting the
Country but associations (with dependent: :destroy) were
deleted whatsoever, as this is a rails bug (see
rails/rails#3458)
@r0qs
Copy link

r0qs commented Aug 23, 2016

Is this still an issue?

@kesha-antonov
Copy link
Contributor

Same

1 similar comment
@lucasocon
Copy link

Same

@pierrea
Copy link

pierrea commented Feb 3, 2017

Still having the same issue here too

@andreiglingeanu
Copy link

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

@xinranxiao
Copy link

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

@vishalzambre
Copy link
Contributor

@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.

@xinranxiao
Copy link

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

@HassanTC
Copy link

HassanTC commented Aug 6, 2017

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

@scooler
Copy link

scooler commented Dec 15, 2020

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 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests