diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb index a09f0db97..564443977 100644 --- a/app/controllers/invites_controller.rb +++ b/app/controllers/invites_controller.rb @@ -15,12 +15,7 @@ class InvitesController < ApplicationController ) if invite.valid? - if invite.user.present? - InviteMailer.invite_user(invite).deliver_later - else - InviteMailer.invite_guest(invite).deliver_later - end - + # The notification is sent through an after commit hook in order to avoir concurrency issues flash.notice = "Une invitation a été envoyée à #{invite.email}." else flash.alert = invite.errors.full_messages diff --git a/app/models/invite.rb b/app/models/invite.rb index 8c51c6e7e..62e9968fd 100644 --- a/app/models/invite.rb +++ b/app/models/invite.rb @@ -19,6 +19,8 @@ class Invite < ApplicationRecord before_validation -> { sanitize_email(:email) } + after_save_commit :send_notification + validates :email, presence: true validates :email, uniqueness: { scope: :dossier_id } @@ -32,4 +34,12 @@ class Invite < ApplicationRecord scope :kept, -> { joins(:dossier).merge(Dossier.kept) } default_scope { kept } + + def send_notification + if self.user.present? + InviteMailer.invite_user(self).deliver_later + else + InviteMailer.invite_guest(self).deliver_later + end + end end