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
You want to use
destroy. Some methods in ActiveRecord do not trigger callbacks,deleteis one of them:https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-delete