ITeye博客

自定义error_messages_for定制校验信息

balaschen · 2007-11-13 11:16 · ror · HTML · Ruby · Markdown

ruby 代码

 

  1. module ApplicationHelper
  2. def error_messages_for(*params)
  3. options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
  4. objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
  5. count   = objects.inject(0) {|sum, object| sum + object.errors.count }
  6. unless count.zero?
  7. html = {}
  8. [:id, :class].each do |key|
  9. 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 << 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) <<
  27. content_tag(:p, '发生以下错误:') <<
  28. content_tag(:ul, error_messages),
  29. html
  30. )
  31. else
  32. ''
  33. end
  34. end
  35. end

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。