Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when the model is destoyed automatically by a :dependent => :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 has been fired by dependent => destroy or not because part of it would/will be done in do_some_stuff

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

any ideas?

like image 262
Sylvain Desbureaux Avatar asked Oct 24 '22 05:10

Sylvain Desbureaux


1 Answers

You can use the association callbacks ( before_remove or 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
like image 51
Harish Shetty Avatar answered Oct 26 '22 21:10

Harish Shetty