将用户输入的URL设置为轨道中的外部链接
我希望用户能够输入url,然后在我的视图中添加指向该url的链接。
有效输入可以是https://www.google.com/path
是否有标准的rails方式1)validation输入是有效的url格式,2)在我的视图中将第三种格式转换为http://www.google.com
,以便外部链接有效吗?
如果我可以避免它,我不想重新发明轮子。
看一下这个:
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
强烈建议使用Domainatrix gem来validationURL: