如何在 Rails 中将 'link_to' 转换为 Absolute

How convert 'link_to' to Absolute in Rails

我的程序有问题,我在数据库中添加了一个 link,例如 "www.google.com",当我点击 link 时,我被重定向到 localhost:3000/www.google.com,当我将“http://www.google.com”放入数据库时​​不会发生这种情况。

我的代码

<td><%= link_to t.title, t.link_to_idea, :target => "_blank" %></td>

如何将此 link 始终转换为绝对值? (我认为这是解决方案)

谢谢!!

你可以这样做:

<td><%= link_to t.title, t.link_to_idea.start_with?('http') ? t.link_to_idea : "http://#{t.link_to_idea}", :target => "_blank" %></td>

..但这假设您希望所有 links 使用 http 而不是 https 保存。 在将 link 保存在数据库中之前,您最好检查协议。

例如,您可以按照此答案的建议进行操作:

before_validation :smart_add_url_protocol

protected

def smart_add_url_protocol
  unless self.url[/\Ahttp:\/\//] || self.url[/\Ahttps:\/\//]
    self.url = "http://#{self.url}"
  end
end

这样你就可以做你已经拥有的。

我认为最好的办法是更新数据库中的链接,使其全部符合标准格式。您还可以添加更基本的验证以确保所有链接都匹配有效格式:

validates :link_to_idea, format: URI.regexp

您还可以 运行 对数据库进行回填,检查旧链接以确保它们与此模式匹配,然后更新无效的链接。您在使用 MySQL 吗?

无论哪种方式,最好的答案不是试图让您的应用程序呈现用户输入的任何旧内容,而是在数据进入数据库之前清理数据。

如果您无法控制进入数据库的内容,那么我会简单地将任何与正则表达式不匹配的内容呈现为文本,然后让用户自行将其放入浏览器中。

我建议您使用 Draper 创建装饰器。这将允许您将表示逻辑与域对象分离。

一旦你设置好了,你就可以写类似这样的东西:

# app/decorators/idea_decorator.rb
class IdeaDecorator < Draper::Decorator
  delegate_all   

  def idea_url(protocol = 'https')
    return link_to_idea if has_scheme?

    "#{protocol}://#{link_to_idea}"
  end

  private

  def has_scheme?
    # .. some method here to determine if the URL has a protocol
  end
end

并在视图中使用:

<%= link_to t.title, t.decorate.idea_url('https') %>