Reputation: 1089
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
Upvotes: 6
Views: 5251
Reputation: 24337
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
Upvotes: 17