1
votes

I am on a rails 5 app. Using devise for user management. I have 'confirmable' enabled in my user model and the migrations are also up for the same. I have created a custom mailer class which is derived from Devise::Mailer, have setup the mailer in devise config to use the custom mailer class however my confirmations email are not being sent properly. Have tried many so answer threads but couldn't crack it yet. Where could I be going wrong?

User Model

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :send_confirmation_email

  def send_confirmation_email
    p 'inside after_create callback func.'
    MyDeviseMailer.confirmation_instructions(self).deliver
  end

end

Migration for confirmable

def up
    add_column :users, :confirmation_token, :string
    add_column :users, :unconfirmed_email, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    add_index :users, :confirmation_token, unique: true
end

My custom mailer class derived from Devise::Mailer

class MyDeviseMailer < Devise::Mailer

  helper :application
  include Devise::Controllers::UrlHelpers
  default template_path: 'devise/mailer'

  def confirmation_instructions(record, token, opts={})
    devise_mail(record, :confirmation_instructions, opts)
  end
end
1

1 Answers

1
votes

After a couple of hours, figured out that i was following the wrong way of doing things.Followed the well written article over here.Have updated my solution below:

Refactored confirmation_instructions method present in my custom mailer class as shown below:

def confirmation_instructions(record, token, opts={})

    if record.email.present?
      opts[:subject] = "Welcome #{record.email.split('@').first.capitalize}, Confirm your asana account"
    else
      opts[:subject] = "Confirm Your Asana Account"
    end

    super

  end

Changed the function invocation to this in my user model:

MyDeviseMailer.confirmation_instructions(self, self.confirmation_token).deliver

This is what worked for me finally.