Вопрос

I can use Devise helper methods in regular views but don't know how to use it within my Mailer. I need to determine if user is signed in to construct proper email message.

class UserMailer < ActionMailer::Base
  def receipt
  end
end

receipt.text.erb

<% if user_signed_in? %> #Error: undefined method `user_signed_in?' for #<#<Class:0x35695fc>
    Secret link
<% end %>
Это было полезно?

Решение

Actually, you can't and most of all, you shouldn't use this kind of Devise helper on your mailer.

Why ? Well, if you search Devise's code base for the user_signed_in? helper, you will find it in Devise::Controllers::Helpers module, as you can see here. This means that it is supposed to be used in a controller context, as it uses method such as request and warden that is only available on controllers.

If you must make any decision in your mail view based on whether a user is signed in or not, I would recommend you to pass this information from your controller to your mailer:

Your controller:

class UserController < ApplicationController
  def your_action
    UserMailer.receipt(user_signed_in?).deliver
    #....
  end
end

Your mailer:

class UserMailer < ActionMailer::Base
  def receipt(signed_in)
    @signed_in = singed_in
    #....
  end 
end

Your mailer view:

<% if @signed_in %>
  Secret link
<% end %>

I hope it helps !

Другие советы

You can pass it over from helper. Something like this

class UserMailer < ActionMailer::Base
  def receipt
    @is_signed = user_signed_in?
  end
end

and

<% if @is_signed %>
  Secret link
<% end %>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top