我有这个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
你尝试'validate_on_create'? – 2011-04-10 11:08:19