Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Different View (template) for ActionMailer

I'm trying to do a conditional render of a different template from ActionMailer (Rails 3.1.1). I want most users to get the normal welcome.html.erb template, but some users to get the special welcome_photographer.html.erb template. This type of thing works in ActionController:

# (in /app/mailers/user_mailer.rb)  def welcome(user)   @user = user   mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...")   render "welcome_photographer" if @user.is_photographer end 

But the render doesn't work -- everyone gets the standard welcome.html.erb even if @user.is_photographer == true

like image 333
brittohalloran Avatar asked Nov 21 '11 22:11

brittohalloran


People also ask

How do I Preview mailers in Rails?

Then the preview will be available in http://localhost:3000/rails/mailers/user_mailer/welcome_email. If you change something in app/views/user_mailer/welcome_email. html. erb or the mailer itself, it'll automatically reload and render it so you can visually see the new style instantly.

How do I send an email to ROR?

Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.


2 Answers

You shouldn't try to do anything after you call mail(). However, to choose another template, you should pass :template_name as an option. For example:

template = @user.is_photographer ? "welcome_photographer" : "welcome" mail(:to => "#{@user.name} <#{@user.email}>",       :subject => "Welcome to ...",       :template_name => template) 
like image 106
Sean Hill Avatar answered Sep 20 '22 22:09

Sean Hill


The solution from Sean Hill doesn't work for me (Rails 3.2+). template_name seems to be ignored. What worked for me is something like this:

mail(:to => "#{@user.name} <#{@user.email}>", :subject => "Welcome to ...") do |format|   format.html { render 'templatename' } end 
like image 35
Malte Avatar answered Sep 20 '22 22:09

Malte