How to generate correct URLs in mailer templates?

user502052 picture user502052 · Jan 12, 2012 · Viewed 8.6k times · Source

I am using Ruby on Rails 3.1.0 and I would like to properly generate URLs in HTML email messages. In my environment file I set

config.action_mailer.default_url_options = { :host => 'my_site.org' }

In the email view file (.html.erb) I state

<%= link_to @user.name, users_url(@user) %>

When I go to see the received email the generated URL is http://users/1, of course no correct. So, how can I generate correct URLs in mailer templates so to have http://my_site.org/users/1 links in body messages?


I also tryed to set the default_url_options in my mailer.rb file

class MyCustom::Mailer < ActionMailer::Base
  default_url_options[:host] = 'my_site.org'

  def test_sending
    ...
  end
end

but it doesn't work.

Answer

MrTheWalrus picture MrTheWalrus · Jan 12, 2012

users_path is the relative path (/users/1). For an email, you want the absolute path, so use users_url(@user), which will give http://myapp.com/users/1 instead.