Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - check if parent object was destroyed and is calling destroy on dependents

I have the following:

class ModelA < ApplicationRecord
  has_many :model_bs, dependent: :destroy
end

class ModelB < ApplicationRecord
  belongs_to :model_a
  after_destroy :action_only_if_model_a_exists

  private

  def action_only_if_model_a_exists
    # Do things
  end
end

When I call model_a.destroy, I need to be able to determine in the action_only_if_model_a_exists callback in ModelB whether the associated ModelA still exists or is also about to be destroyed.

Is there a nice inbuilt Rails way of doing this or do I need to go down the path of setting a flag in ModelA in an earlier callback (e.g. before_destroy) which I can then check in ModelB's callback?

Edit

I have done multiple tests and confirmed that inside the action_only_if_model_a_exists callback, doing the following doesn't help:

> model_a.persisted?
true

> model_a.destroyed?
false

> model_a.frozen?
false
like image 932
bdx Avatar asked Oct 28 '25 11:10

bdx


1 Answers

You can use the destroyed_by_association attribute in the child to see if the object is being destroyed as part of the dependent: :destroy from it's parent.

like image 112
cpjolicoeur Avatar answered Oct 30 '25 01:10

cpjolicoeur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!