How to find out when a model automatically shuts down: depend =>: destroy in rails?

I have the following association:

class Parent < ActiveRecord::Base
  has_many :children, :dependent => :destroy
  before_destroy :do_some_stuff
end

class Child < ActiveRecord::Base
  belongs_to :parent
  before_destroy :do_other_stuff
end

I would like to know in do_other_stuff if the destruction was fired by the dependent => destroy or not, because part of it will / will be done in do_some_stuff

I tried parent.destroyed?, parent.marked_for_destruction?, parent.frozen?but nothing seems to work: /

any ideas?

+5
source share
2 answers

You can use association callbacks ( before_removeor after_remove)

class Parent < ActiveRecord::Base
  has_many :children, :dependent => :destroy, :before_remove => :do_foo

  before_destroy :do_bar

  def do_bar
  end

  def do_foo
  end
end
+3
source

Maybe something like this:

class Parent < ActiveRecord::Base
    has_many :children
    before_destroy :some_stuff
    def some_stuff
        children.each do |child|
            child.parent_say_bye
        end
    end
end

class Child < ActiveRecord::Base
    belongs_to :parent
    before_destroy :do_other_stuff
    def parent_say_bye
        #do some stuff
        delete
    end
end
0
source

All Articles