How to access current_user in rails action mailer

Hi, I need to access the current user in my mail program, but I get the following error

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

using this link I use the application helper to get 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 the current user in the action mail program. I am using Rails 3.2.14 and ruby ruby 2.1.0

+6
source share
1 answer

Do not try to access current_user from inside Mailer. Instead, pass the user to the mailer method. For instance,

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

To use it from the controller, where you have access to current_user :

 WelcomeMailer.welcome_email(current_user).deliver 

From the model:

 class User < ActiveRecord::Base after_create :send_welcome_email def send_welcome_email WelcomeMailer.welcome_email(self).deliver end end 
+12
source

Source: https://habr.com/ru/post/974294/


All Articles