How to pass instance variable to devise custom mailer in Rails?

别等时光非礼了梦想. 提交于 2019-12-14 03:30:55

问题


I am using custom mailer by overriding the devise mailer. It is working fine. But I need to pass some data to the mailer template so that when the confirmation email send to the user it contains some dynamic content. I have tried it using sessions,@resource and current_user method but both are not working. Is there any way to do that? Custom mailer

class CustomMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer' # to make sure that you mailer uses the devise views

  def confirmation_instructions(record, token, opts={})
      opts[:subject] = "Email Confirmation"
      opts[:from] = 'no-reply@abc.com'
      @data = opts[:custom_field]
    super
  end

end

in the controller

CustomMailer.confirmation_instructions(token, {custom_field: "abc"})

This is the code in template

We are happy to invite you as user of the <b>  <%= @data %> </b> 

Thanks.


回答1:


First, read about Devise custom mailer to familiarize yourself with the process.

Briefly this is how you'd go about doing it:

in config/initializers/devise.rb:

config.mailer = "DeviseMailer"

Now you can just use DeviseMailer like you'd do for any other mailer in your project:

    class DeviseMailer < Devise::Mailer   
      helper :application # gives access to all helpers defined within `application_helper`.
      include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
      default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views
     ...

    def invite(sender, recipient)
      @sender = sender
      @recipient = recipient

      mail( :to => recipient.email,
          :subject => "Invite by #{sender.name}"
        )
    end
      ...
   end

You can now call the invite in your project and pass whatever variable you want to be able to access in your template.

i.e:

Calling the invite method:

DeviseMailer.invite(current_user, newContact).deliver

So in your view you can then just call the variable:

invite.html.erb

<p>Hello <%= @recipient.email %></p>

<% if @sender.email? %>
  <p> some additional welcome text here from <%= @sender.email %> </p>
<% end %>

EDIT

To answer your specific question here is what you want to override:

def confirmation_instructions(record, token, opts={})
  headers["Custom-header"] = "Bar"
  opts[:from] = 'my_custom_from@domain.com'
  opts[:reply_to] = 'my_custom_from@domain.com'
  super
end

Then call it anywhere you want:

 DeviseMailer.confirmation_instructions(User.first, "faketoken", {})


来源:https://stackoverflow.com/questions/47184816/how-to-pass-instance-variable-to-devise-custom-mailer-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!