From cc5cd47de086c075999fecec258dc45f3d5cdd65 Mon Sep 17 00:00:00 2001 From: vangberg Date: Mon, 29 Jun 2026 11:30:32 +0200 Subject: [PATCH] Send mails in after commit hook AsyncAdapter will run jobs immediately. When a mail is sent via `perform_later` in an `after_create` hook, the job could run before the record exists in the database, since `after_create` hooks are executed *before* the transaction is completed. --- app/models/contact.rb | 4 +++- app/models/notification.rb | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/models/contact.rb b/app/models/contact.rb index 342af882..ca933a19 100644 --- a/app/models/contact.rb +++ b/app/models/contact.rb @@ -11,7 +11,9 @@ class Contact < ApplicationRecord has_rich_text(:message) - after_create(:send_message) + # Enqueue email only after commit to avoid timing issues where the job runs + # before the contact creation is visible outside the transaction. + after_create_commit(:send_message) def default_message <<~MSG diff --git a/app/models/notification.rb b/app/models/notification.rb index cdb94148..8d223e08 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -3,7 +3,9 @@ class Notification < ApplicationRecord belongs_to :notifiable, polymorphic: true belongs_to :linkeable, polymorphic: true, optional: true - after_create(:send_email_notification) + # Enqueue email only after commit to avoid timing issues where the job runs + # before the notification creation is visible outside the transaction. + after_create_commit(:send_email_notification) after_save(:broadcast_notification_count) after_create(:broadcast_web_notification)