2011-04-10 93 views
2

我有这个ruby类的链接数组。现在,即使数组包含的链接不是有效的URL,我仍可以保存Paper对象。我有一个方法遍历数组并验证url,如果url无效,则返回false。但是当我尝试调用Paper.save时,我想获得一条错误消息。那可能吗?MongoMapper自定义验证

class Paper 
    include MongoMapper::Document 

    key :links,  Array 

    validates_presence_of :links 

    def validate_urls 
    reg = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix 
    status = [] 
    links.each do |link| 
     if link.match(reg) 
     status.push('true') 
     else 
     if "http://#{link}".match(reg) 
      status.push('true') 
     else 
      status.push('false') 
     end 
     end 
    end 
    if status.include?('false') 
     return false 
    else 
     return true 
    end 
    end 

end 
+0

你尝试'validate_on_create'? – 2011-04-10 11:08:19

回答

5

如果您使用从GitHub MongoMapper(其中加载ActiveModel支持),见http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate

class Paper 
    include MongoMapper::Document 

    key :links,  Array 

    validates_presence_of :links 
    validate :validate_urls 

    def validate_urls 
    reg = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix 
    status = [] 
    links.each do |link| 
     if link.match(reg) 
     status.push('true') 
     else 
     if "http://#{link}".match(reg) 
      status.push('true') 
     else 
      status.push('false') 
     end 
     end 
    end 
    if status.include?('false') 

     # add errors to make the save fail 
     errors.add :links, 'must all be valid urls' 

    end 
    end 

end 

不知道这代码,是用0.8.6宝石,但它可能。

而且,它不适用于这种情况,但如果它不是一个数组,你可以粉碎一切转化为一个单行:

key :link, String, :format => /your regex here/ 
+0

它似乎不适用于我拥有的宝石。虽然我不会尝试从源代码创建宝石。 – schwift 2011-04-12 22:10:02

+0

啊哈 - 在'errors.add'之前摆脱'return false'帮助很大。 – schwift 2011-04-13 17:11:36