CodexBloom - Programming Q&A Platform

Unexpected behavior with Rails 7's `after_save` callback when using nested transactions

πŸ‘€ Views: 457 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
ruby-on-rails callbacks transactions active-record ruby

I'm encountering an issue with the `after_save` callback in my Rails 7 application where it seems to not execute as expected when the model is being saved within a nested transaction..... I have a model called `Order` which has a callback to send a confirmation email after it's saved. However, when I run the following code, the email is not being sent when I wrap the creation of an `Order` in a transaction block: ```ruby ActiveRecord::Base.transaction do order = Order.new(user_id: @user.id, total: 100) if order.save # some logic that may trigger another transaction place_order(order) end end ``` The `place_order` method contains another transaction where I've noticed that the callback for sending the email is skipped: ```ruby def place_order(order) ActiveRecord::Base.transaction do # Some additional operations end end ``` I would expect the email to be sent as part of the `after_save` callback, but it seems that the callback is not firing, likely due to the nested transactions. I even tried adding `:on => :create` to my `after_save` callback, but that didn't help. Here’s how I’ve defined the callback in the `Order` model: ```ruby class Order < ApplicationRecord after_save :send_confirmation_email private def send_confirmation_email UserMailer.with(order: self).confirmation.deliver_later end end ``` I've checked the logs, and I see the order is being saved correctly, but the email delivery is not logged, indicating that the callback isn't executing. Is there a best practice or workaround for using callbacks with nested transactions in Rails 7? Any insight would be greatly appreciated! This is part of a larger application I'm building. Has anyone else encountered this? I appreciate any insights!