In the mailer class that you are using to manage your emails:
class ReportMailer < ActionMailer::Base
add_template_helper(AnnotationsHelper)
...
end
In Rails 3, just use the helper method at the top of your ActionMailer class:
helper :mail # loads app/helpers/mail_helper.rb & includes MailHelper
I just passed in a block, since I only need it in the one Mailer:
helper do
def host_url_for(url_path)
root_url.chop + url_path
end
end
(be sure to set config.action_mailer.default_url_options.)
(and if you use url_for, be sure to pass in :only_path => false)
For all mailers in Rails 3 (setting "application" helper):
# config/application.rb:
...
config.to_prepare do
ActionMailer::Base.helper "application"
end
For Ruby on Rails 4, I had to do 2 things:
(1) As Duke already said, if the helper you want to add is UsersHelper
for example, then add
helper :users
to the derived ActionMailer
class (e.g. app/mailers/user_mailer.rb
)
(2) After that, I got a new error:
ActionView::Template::Error (Missing host to link to! Please provide the :host
parameter, set default_url_options[:host], or set :only_path to true)
To fix this, add the line
config.action_mailer.default_url_options = { :host => 'localhost' }
to each of the config/environments/*.rb
files. For config/environments/production.rb
, replace localhost
with a more appropriate host for the production helper-generated urls.
Q: For #2, why does the mail view need this information, and the regular views do not?
A: Because the regular views don't need to know the host
, since all generated links are served from the host they link to. Links that show up in emails are not served from the same host (unless you are linking to hotmail.com
or gmail.com
, etc.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With