34

I'm working on a website that allows users to create an account. One of the attributes when creating a user is a users personal website. When I try to use the users website like this:

<%= link_to @user.site, @user.url %>

The url that gets generated is: http://0.0.0.0:3000/www.userswebsite.com

I think this is because of the @user part of the link_to... but how can I get this to link to www.userwebsite.com ?

Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156
thedeepfield
  • 6,138
  • 25
  • 72
  • 107

4 Answers4

97

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

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

And then:

link_to @user.site, url_with_protocol(@user.url), :target => '_blank'
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Voldy
  • 12,829
  • 8
  • 51
  • 67
  • 2
    Use :target => '_blank' instead of :target => :blank. It doesn't work as expected, you can try it by opening the same link from the newly created window. – dostu Apr 02 '12 at 02:51
  • If my URL doesn't include `www.` then my app considers it an internal link. E.g. `http://example.com` links to the current page. – Dennis May 06 '14 at 15:34
28

Looks like you need to stick the protocol on your link. E.g. you have www.userswebsite.com in your database, it should be http://www.userswebsite.com

cam
  • 14,192
  • 1
  • 44
  • 29
  • 1
    this works but relies on being able to always keep a sanitized url in the database, which may not always be possible...see the Voldy answer for one that sanitizes on its way out – rogerdpack Sep 05 '14 at 14:31
3

You are storing URLs without the http:// so they are being interpreted as relative URLs. Try this: link_to @user.site, "http://#{@user.url}"

Anshul Garg
  • 313
  • 1
  • 3
  • 14
1

Try out the awesome gem Domainatrix:

Then you can simply parse the URL on the fly with:

<%= Domainatrix.parse(@user.url).url %>

Better yet, create a before_save action in your user model that parses the url before saving it.

before_save :parse_url

def parse_url
  if self.url
    self.url = Domainatrix.parse(self.url).url
  end
end

Here are some samples of what you can do with Domainatrix:

url = Domainatrix.parse("http://www.pauldix.net")
url.url       # => "http://www.pauldix.net" (the original url)
url.public_suffix       # => "net"
url.domain    # => "pauldix"
url.canonical # => "net.pauldix"

url = Domainatrix.parse("http://foo.bar.pauldix.co.uk/asdf.html?q=arg")
url.public_suffix       # => "co.uk"
url.domain    # => "pauldix"
url.subdomain # => "foo.bar"
url.path      # => "/asdf.html?q=arg"
url.canonical # => "uk.co.pauldix.bar.foo/asdf.html?q=arg"
Abram
  • 39,950
  • 26
  • 134
  • 184