How to stop links in rails app being prefixed with domain

464 Views Asked by At

Both of these:

<%= content_tag("a", @a_model_instance.name, :href => @a_model_instance.url) %>
<a href="<%= @a_model_instance.url %>"><%= @a_model_instance.url %></a>

result in urls with href values of:

0.0.0.0:3000/model_name/www.the_url_i_want.com

How do you prevent this to get a tags with href values of www.the_url_i_want.com? @a_model_instance.urlreturns the string www.the_url_i_want.com.

edit - one solution

This works:

<%= content_tag("a", @a_model_instance.name, :href => "http://#{@a_model_instance.url}") %>
<a href="http://<%= @a_model_instance.url %>"><%= @a_model_instance.url %></a>

But seems very non-railsy

3

There are 3 best solutions below

0
On BEST ANSWER

if you add http at the beginning of the url it shouldnt prepend the domain I think

2
On

You can insert the url raw

 <%= link_to "Visit Stackoverflow", "http://www.stackoverflow.com/" %>

or try

<%= link_to "My url string", "#{@a_model_instance.url}" %>
0
On

You can prepend url with protocol if it's absent:

module UrlHelper
  def url_with_protocol(url)
    /^http/.match(url) ? url : "http://#{url}"
  end
end

And then:

link_to @a_model_instance.name, url_with_protocol(@a_model_instance.url)