Ruby-on-rails RAILS 链接到外部站点,url 是用户表的属性,如:@users.website

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5012188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:26:18  来源:igfitidea点击:

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

ruby-on-railsrubyhyperlinkexternallink-to

提问by thedeepfield

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

生成的网址是: 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 ?

我认为这是因为 link_to 的 @user 部分...但是我怎样才能让它链接到 www.userwebsite.com ?

采纳答案by cam

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

看起来您需要在链接上粘贴协议。例如,您的数据库中有 www.userswebsite.com,它应该是http://www.userswebsite.com

回答by Voldy

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

如果不存在,您可以在 url 前面加上协议:

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'

回答by Anshul Garg

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

您存储的 URL 没有 http://,因此它们被解释为相对 URL。试试这个:link_to @user.site, " http://#{@user.url}"

回答by Abram

Try out the awesome gem Domainatrix:

试试很棒的 gem Domainatrix

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

然后你可以简单地动态解析 URL:

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

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

更好的是,before_save在您的用户模型中创建一个操作,在保存之前解析 url。

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:

以下是您可以使用 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"