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, @us开发者_运维知识库er.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 ?
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'
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
You are storing URLs without the http:// so they are being interpreted as relative URLs. Try this: link_to @user.site, "http://#{@user.url}"
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"
精彩评论