RAILS link_to external site, url is attribute of user table, like: @users.website

只谈情不闲聊 提交于 2019-11-27 11:31:44

问题


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 ?


回答1:


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




回答2:


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'



回答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}"




回答4:


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"


来源:https://stackoverflow.com/questions/5012188/rails-link-to-external-site-url-is-attribute-of-user-table-like-users-websit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!