kuwantum
kuwantum

Reputation: 314

Unable to call "current_user" while using Devise

I am currently working on a Rails app which has language support for English, Japanese, and Chinese - based on which site a user signs up from, the database will store their language (JP = 0, EN = 1, ZH = 2). For the emails sent out to users based on various actions (making a reservation, making changes to accounts etc) I want to call current_user.language and make changes based on the result like so:

def set_language
    if current_user.language = 1
        I18n.locale = 'en'
    elsif current_user.language = 2
        I18n.locale = 'zh'
    else
    I18n.locale = 'ja'
    end
end

(NOTE: JP is the default)

Unfortunately, I always get the following error message:

undefined local variable or method 'current_user' for #<ReservationMailer:0x007f944682a7f8>

and I have not been able to find a solution.

In the past, having Devise installed has always allowed me to call this without issue - I am now working on a project that was started by others some time ago and can not work out why it refuses to work. Please let me know if I can provide any further useful points.

Also, I checked the routes and devise is correctly set there via devise_for :users.

Upvotes: 1

Views: 350

Answers (2)

Roshan
Roshan

Reputation: 915

current_user is a method that is available only to views and controllers. If you want to use it in a mailer or model, it will have to be explicitly used as an argument for the mailer method.

Inside the controller create method:

ReservationMailer.set_language(current_user).deliver

Mailer method:

def set_language(user)
    if user.language = 1
        I18n.locale = 'en'
    elsif user.language = 2
        I18n.locale = 'zh'
    else
    I18n.locale = 'ja'
    end
end

Mailer view:

<table>
  <tr>
    <td>name</td>
    <td><%= @user.firstname %><%= @user.firstname  %></td>
  </tr>
  <tr>
    <td>phone no.</td><td><%= @user.phone %></td>
  </tr>
</table>

Upvotes: 1

Thanh
Thanh

Reputation: 8604

current_user is a helper that is only used for controllers/views. You can not use it in another place, like your ReservationMailer. In your case, if you call method set_language from controller, you can pass current user id to set_language method.

def set_language(user_id)
    current_user = User.find(user_id)

    if current_user.language = 1
        I18n.locale = 'en'
    elsif current_user.language = 2
        I18n.locale = 'zh'
    else
    I18n.locale = 'ja'
    end
end

Upvotes: 1

Related Questions