scoots
scoots

Reputation: 715

Dependent Destroy not working with soft deleted parent in Rails

Here's the code:

class SomeParent < ActiveRecord::Base

    has_one :some_child, dependent: :destroy

    def destroy
       self.update_attributes(deleted_at: Time.now)
    end

    def deleted?
       deleted_at.present?
    end
end

Can somebody explain why? Also, is there generally a more preferred way to handle this?

Upvotes: 1

Views: 678

Answers (2)

Brad Werth
Brad Werth

Reputation: 17647

When the destroy method was overridden, the callback applied to the original definition was not applied to the overridden method. A simple fix is to wrap your code with the desired callback, like so:

def destroy
  run_callbacks :destroy do
    self.update_attributes deleted_at: Time.now
  end
end

Upvotes: 2

ilan berci
ilan berci

Reputation: 3881

The reason is that the code above overrode the ActiveRecord::Base.destroy() which takes care of all the dependents.

Upvotes: 0

Related Questions