---
title: "自定义error_messages_for定制校验信息"
author: "balaschen"
date: "2007-11-13T11:16:53Z"
tags: ["HTML", "Ruby"]
slug: "error-messages-for"
draft: false
lastmod: "2007-11-13T11:16:53Z"
id: 140137
url: "https://balaschen.iteye.com/blog/140137"
---

ruby 代码

 

01. module ApplicationHelper
02. def error\_messages\_for(\*params)
03. options = params.last.is\_a?(Hash) ? params.pop.symbolize\_keys : {}
04. objects = params.collect {|object\_name| instance\_variable\_get("@#{object\_name}") }.compact
05. count   = objects.inject(0) {|sum, object| sum + object.errors.count }
06. unless count.zero?
07. html = {}
08. \[:id, :class].each do |key|
09. if options.include?(key)
10. value = options\[key]
11. html\[key] = value unless value.blank?
12. else
13. html\[key] = 'errorExplanation'
14. end
15. end
16. header\_message = ""#"#{pluralize(count, 'error')} prohibited this #{(options\[:object\_name] || params.first).to\_s.gsub('\_', ' ')} from being saved"
17. #error\_messages = objects.map {|object| object.errors.full\_messages.map {|msg| content\_tag(:li, msg) } }
18. error\_messages = objects.map do |object|
19. full\_messages = \[]
20. object.errors.each do |attr,msg|
21. full\_messages &lt;&lt; msg unless msg.nil? || msg.blank?
22. end
23. full\_messages.map{|msg| content\_tag(:li,msg)}
24. end
25. content\_tag(:div,
26. content\_tag(options\[:header\_tag] || :h2, header\_message) &lt;&lt;
27. content\_tag(:p, '发生以下错误:') &lt;&lt;
28. content\_tag(:ul, error\_messages),
29. html
30. )
31. else
32. ''
33. end
34. end
35. end