Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute URL's with link_to...Ruby on Rails

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)

like image 577
Chris Muench Avatar asked Feb 25 '11 12:02

Chris Muench


People also ask

How can you get the current absolute URL in your Ruby on Rails view?

You should use request. original_url to get the current URL.

Is absolute URL better than relative?

An absolute URL contains more information than a relative URL does. Relative URLs are more convenient because they are shorter and often more portable. However, you can use them only to reference links on the same server as the page that contains them.

Which is an example of an absolute URL?

An absolute URL is the full URL, including protocol ( http / https ), the optional subdomain (e.g. www ), domain ( example.com ), and path (which includes the directory and slug).

How do you make an absolute URL?

If you prefix the URL with // it will be treated as an absolute one. For example: <a href="//google.com">Google</a> . Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com ).


2 Answers

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 %> 
like image 111
Simone Carletti Avatar answered Sep 24 '22 04:09

Simone Carletti


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

link_to(body, "http://#{site_url}") 
like image 28
Simon Liu Avatar answered Sep 22 '22 04:09

Simon Liu