rodrigoalves rodrigoalves - 1 year ago 228
Ruby Question

Rails 4.1 Mailer Previews and Devise custom emails

I have a brand new Rails 4.1.1 app where I'm customizing the Devise emails. I want to have them displayed on the new Rails email preview feature so I did the following:

1) Added the following snippet to my


config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"

2) Created my custom Devise email

class UserMailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`

layout "notifications_mailer"

3) Changed
to contain the following snippet:

config.mailer = 'UserMailer'

4) Added the class
with the following content:

class UserMailerPreview < ActionMailer::Preview
def confirmation_instructions
UserMailer.confirmation_instructions(User.first, {})

def reset_password_instructions
UserMailer.reset_password_instructions(User.first, {})

def unlock_instructions
UserMailer.unlock_instructions(User.first, {})

So far, so good. Looks like I've done everything right. But then I try to see the preview for the
email at the /rails/mailers/user_mailer/confirmation_instructions route and I get the following error:

undefined method `confirmation_url' for #<#<Class:0x007fa02ab808e0>:0x007fa030fb7e80>

the code for my
template looks like this:

<%= t("notifications.texts.greeting") + @user.display_name %>,

<p>You can confirm your account email through the link below:</p>

<p><%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @token) %></p>

What am I doing wrong? I guess it is something wrong with the way I call the
method. Anyone can help me here?

Answer Source

I found this question because I was trying to figure out how to preview Devise emails myself. I copied your code almost exactly and it works fine for me.

The only thing I did differently was to remove the line layout "notifications_mailer" from UserMailer - when I included it I got an error message Missing template layouts/notifications_mailer. What happens if you remove it?

The line Devise::Controllers::UrlHelpers definitely includes the method confirmation_url (you can see this for yourself by opening up the Rails console and running include Devise::Controllers::UrlHelpers then confirmation_url, so I suspect the problem is that your previews aren't being rendered by UserMailer at all. I'm not sure why, but the line layout "notifications_mailer" might be the culprit.

Do you have a class called NotificationsMailer? Does including Devise::Controllers::UrlHelpers in there solve your problem?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download