6

Hi I have to access the current user into my action mailer, but I getting following error

undefined local variable or method `current_user' for #<WelcomeMailer:0xa9e6b230>

by using this link I am using application helper for getting the current user. Here is my WelcomeMailer

class WelcomeMailer < ActionMailer::Base
  layout 'mail_layout'

  def send_welcome_email
    usr = find_current_logged_in_user
    Rails.logger.info("GET_CURRENT_USER_FROM_Helper-->#{usr}")
  end
end

and my application helper is as follows

def find_current_logged_in_user
    #@current_user ||= User.find_by_remember_token(cookies[:remember_token])
    # @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id])
    Rails.logger.info("current_user---> #{current_user}")
    current_user
  end

Also I tried with session and cookies. So how can I resolve this error or is there any other method for accessing current user in action mailer. I am using Rails 3.2.14 and ruby ruby 2.1.0

Community
  • 1
  • 1
user2622247
  • 1,059
  • 2
  • 15
  • 26

1 Answers1

17

Don't try to access current_user from inside a Mailer. Instead, pass the user into the mailer method. For example,

class WelcomeMailer < ActionMailer::Base
  def welcome_email(user)
    mail(:to => user.email, :subject => 'Welcome')       
  end
end

To use it from within a contoller, where you have access to current_user:

WelcomeMailer.welcome_email(current_user).deliver

From within a model:

class User < ActiveRecord::Base
  after_create :send_welcome_email

  def send_welcome_email
    WelcomeMailer.welcome_email(self).deliver
  end
end
infused
  • 24,000
  • 13
  • 68
  • 78