Error Messages for Rails 3


/ Published in: Rails
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # Andrew Wayne 2010
  2. # Error messages for Ruby on Rails 3
  3. # This isnt available in Rails 3 and is a custom module
  4. # made to work like the previous Rails
  5.  
  6.  
  7. # Put this in your ApplicationHelper or create an error_messages_helper.rb file
  8. # in your helpers dir
  9.  
  10. #------------- START --------------#
  11.  
  12. module ErrorMessagesHelper
  13. # Render error messages for the given objects.
  14. # The :message and :header_message options are allowed.
  15. def error_messages_for(*objects)
  16. messages = objects.compact.map { |o| o.errors.full_messages }.flatten
  17. unless messages.empty?
  18. content_tag(:div, :class => "error_messages") do
  19. list_items = messages.map { |msg| content_tag(:li, msg) }
  20. content_tag(:ul, list_items.join.html_safe)
  21. end
  22. end
  23. end
  24.  
  25. module FormBuilderExtensions
  26. def error_messages(options = {})
  27. @template.error_messages_for(@object, options)
  28. end
  29. end
  30. end
  31.  
  32. ActionView::Helpers::FormBuilder.send(:include, ErrorMessagesHelper::FormBuilderExtensions)
  33.  
  34. # -------------------------------- END ---------------------------------------------- #
  35.  
  36.  
  37. # Example Usage
  38.  
  39. # in UsersController
  40. @user = User.new(params[:user])
  41.  
  42. # in Views
  43. <%= error_messages_for (@user) %>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.