Niall Paterson
Niall Paterson

Reputation: 3580

Rails mail function sending emails twice

Two emails are being sent by the code below, both with an identical message-ID, yet I suspect its probably my code.

controller:

 @payment.update_attributes(:status => "Confirmed")

Payments Modal:

before_save :check_if_confirmed
before_update :check_if_confirmed

def check_if_confirmed
  if status == "Confirmed"
    tickets.each do |t|
     t.status = "Confirmed"
     t.save
  end
    Emailer.payment(self,user.id,user.full_name, user.email, self.total, self.id).deliver
end

Emailer.rb

def payment(payment, user_id, buyer_name, email = payment.user.email, price, payment_id)
....
   mail(:from => "John Smith <[email protected]>", :to => email, :subject => "Whatever")

The email is being sent once then immediately being sent again. Its a receipt so naturally I need to stop it being sent twice.

Thoughts?

Upvotes: 1

Views: 1287

Answers (2)

abhilash
abhilash

Reputation: 71

This is happening because of the callbacks before_save :check_if_confirmed before_update :check_if_confirmed

Use only one of them

Upvotes: 0

Hck
Hck

Reputation: 9167

before_save :check_if_confirmed is fired every time the record is being saved (even if its created)

before_update :check_if_confirmed is fired when record was already created and the data is just updated.

You are using the wrong callbacks, that are firing mail delivering twice. before_save should be enough.

Upvotes: 3

Related Questions