我有這個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