Why is my ActiveRecord (v6) `before_destroy` callback not firing?

71 Views Asked by At

I have a model where X can contain many Y's, and a Y can contain many Z's. It's a tree -- a child can not belong to more than one parent.

The put statements show me that the before_destroy callback isn't firing when I call y.delete, but the delete method is.

I can obviously just put the hook in the delete method, but am curious why the destroy callback doesn't work. I have before_create callbacks in this app, and they work fine.

class Y < ApplicationRecord
  before_destroy :do_before_destroy, prepend: true
  belongs_to :x
  has_many :zs, dependent: :destroy

  def delete
    puts "in delete"
    super
  end

private

  def do_before_destroy
    puts "do_before_destroy"
    self.zes.destroy_all
  end
end
1

There are 1 best solutions below

1
Alex On

You want to use destroy. Some methods in ActiveRecord do not trigger callbacks, delete is one of them:

The row is simply removed with an SQL DELETE statement on the record’s primary key, and no callbacks are executed.
...
To enforce the object’s before_destroy and after_destroy callbacks or any :dependent association options, use destroy.

https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-delete