将用户输入的URL放入rails中的外部链接

时间:2011-11-16 16:57:02

标签: ruby ruby-on-rails-3

我希望用户能够输入网址,然后在我的视图中添加指向该网址的链接。

有效输入可以是e.x. https://www.google.com/pathhttp://www.google.comwww.google.com

是否有标准的rails方式1)验证输入是否是有效的url格式?2)在我的视图中将第三种格式转换为http://www.google.com,以便外部链接有效?

如果可以避免,我不想重新发明轮子。

2 个答案:

答案 0 :(得分:9)

检查出来:

validates_format_of :website, :with => URI::regexp(%w(http https))  

来源:http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company

要格式化缺少协议的URL(http或https),我会做一个pre_save挂钩,如果它丢失则会预先添加它:

before_save :format_url

...

def format_url
  self.website = "http://#{self.website}" unless self.website[/^https?/]    
end

答案 1 :(得分:1)

强烈建议使用Domainatrix gem来验证网址:

https://github.com/pauldix/domainatrix