29

Is it possible to generate absolute URL's in rails using link to? [NOTE: THIS IS IN A MAILER]

I tried to do:

<%= link_to root_url, root_url%>

But I get a runtime error:

*Missing host to link to! Please provide :host parameter or set default_url_options[:host]*

I need this to be dynamic because the application will run on a wildcard domain (*.domain.com)

Chris Muench
  • 17,444
  • 70
  • 209
  • 362
  • Why do you need the URL to be absolute in this case? A relative URL will be relative to the current host, which sounds like what you want – Gareth Feb 25 '11 at 13:11
  • The only reason I can think of is that it's because this link is going to be embedded in an e-mail. Is that what's happening here Chris? – Paul Russell Feb 25 '11 at 13:34
  • appears possible using :only_path => false see http://stackoverflow.com/q/9389874/32453 – rogerdpack Jan 16 '14 at 20:37
  • http://blog.grepruby.com/2015/04/absolute-url-full-url-in-rails-4.html – user3118220 Apr 17 '15 at 12:31

4 Answers4

51

If you use the _url suffix, the generated URL is absolute. Use _path to get a relative URL.

<%= link_to "Home", root_url %>

<%= link_to "Home", root_path %>
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
7

Depending on your use case, string interpolation might be a good solution:

link_to(body, "http://#{site_url}")
user456584
  • 86,427
  • 15
  • 75
  • 107
Simon Liu
  • 463
  • 5
  • 12
4

I found this plugin:

http://www.simonecarletti.com/blog/2009/10/actionmailer-and-host-value/

and it works great!

Chris Muench
  • 17,444
  • 70
  • 209
  • 362
0

In routes.rb insert :

root :to => 'controller#action'

Or replace your current map.root with the correct one.

See documentation about this : routes.rb usage

Awea
  • 3,163
  • 8
  • 40
  • 59