Question

The view helpers in my Mailer template give me relative URLs to the stylesheet and images. Of course, this won't work if I'm viewing the email in Gmail, for example.

In apps/views/layouts/mailer.html.erb

<%= stylesheet_link_tag "application" %>
...
<%= link_to(image_tag("logo.png"), "http://mysite.com") %>

Renders as:

<link href="/assets/application-c90478153616a4165babd8cc6f4a28de.css" media="screen" rel="stylesheet" type="text/css" />
...
<a href="http://mysite.com"><img alt="Logo" src="/assets/logo-d3adbf8d0a7f7b6473e2130838635fed.png" /></a>

How do I get Rails to give me absolute links instead? I'm on Rails 3.1, the asset pipeline is in effect.

Was it helpful?

Solution

`config.action_controller.asset_host handles the host prefix in views generated from an ActionController.

For anything generated in an email you're looking for the ActionMailer configuration options, more specifically:

  • ActionMailer::Base.asset_host will handle your image_tags and
  • ActionMailer::Base.default_url_options[:host] will look after your link_to tags.

eg:

ActionMailer::Base.asset_host                 = "http://blah.com"
ActionMailer::Base.default_url_options[:host] = "blah.com"

Note that you don't need to specify the http prefix for the default url host, you will for the asset host.

I have specified these inside my environment.rb after the application initializer. I would recommend setting an application configuration variable for each environments domain.

OTHER TIPS

For rails 3.2 and ActionMailer use:

config.action_mailer.asset_host = "http://www.example.com"

This might be a bit of a hack, but if you specify an asset host, all helpers will take it into account when rendering links. So if you set

config.action_controller.asset_host = "http://mysite.com"

in your config, stylesheet_link_tag will include the host name.

In this thread rocketscientist and Joe asked about other ideas:

http://apidock.com/rails/ActionView/Helpers/AssetTagHelper/stylesheet_link_tag

You can generate full css as follows (if you do not care about asset hosting). However answer by David Radcliffe should work.

stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
  <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top