CodexBloom - Programming Q&A Platform

ActiveRecord callback not triggering after `destroy` in Ruby on Rails 7.0

πŸ‘€ Views: 62 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-04
ruby rails activerecord Ruby

I'm working on a project and hit a roadblock. I'm working with an scenario where an `after_destroy` callback in my Rails 7.0 application doesn't seem to be executing as expected. I have the following model structure: ```ruby class User < ApplicationRecord has_many :posts, dependent: :destroy after_destroy :log_deletion private def log_deletion Rails.logger.info "User #{id} has been deleted" end end class Post < ApplicationRecord belongs_to :user end ``` When I try to delete a `User` record, I expect the `log_deletion` method to be called, but it doesn't seem to trigger. Here’s the code I used to delete the user: ```ruby user = User.find(1) user.destroy ``` I've confirmed that the user exists and that there are no validation issues preventing the deletion. I also checked the logs for any SQL errors, but nothing seems amiss. The `before_destroy` callback works fine, as I'm able to log messages there. I tried placing a `puts` statement inside the `log_deletion` method, but there's no output in the logs. Additionally, I’ve verified that the `dependency` option is set to `:destroy` correctly on the `has_many :posts` association, so all posts are deleted when the user is deleted. Could there be something I'm missing or a configuration in Rails 7.0 that affects the execution of `after_destroy` callbacks? Any insight would be greatly appreciated! Could this be a known issue? For context: I'm using Ruby on macOS.