2009-01-25 80 views
0

我检出了boththese之前问过的问题,它们对我的情况有帮助但不是完整的解决方案。友好表单验证(Rails)

本质上,我需要从窗体验证用户提交的URL。 // HTTPS://或ftp://:我已经通过验证,它以http开始启动

class Link < ActiveRecord::Base 
    validates_format_of [:link1, :link2, :link3, 
     :link4, :link5], :with => /^(http|https|ftp):\/\/.*/ 
end 

这能很好的完成它在做什么,但我需要进一步去这两个步骤:

  1. 应该允许用户如果需要离开表单字段为空,
  2. 如果由用户提供的网址没有以http://(说他们输入google.com,例如),它应该通过验证,但在处理时添加http://前缀。

我很难确定如何使这项工作干净有效。

回答

3

仅供参考,您不必将数组传递到validates_format_of。 Ruby将自动执行数组(Rails分析*args的输出)。

因此,对于你的问题,我会去这样的事情:

class Link < ActiveRecord::Base 
    validate :proper_link_format 

    private 

    def proper_link_format 
    [:link1, :link2, :link3, :link4, :link5].each do |attribute| 
     case self[attribute] 
     when nil, "", /^(http|https|ftp):\/\// 
     # Allow nil/blank. If it starts with http/https/ftp, pass it through also. 
     break 
     else 
     # Append http 
     self[attribute] = "http://#{self[attribute]}" 
     end 
    end 
    end 
end