Skip to content

Instantly share code, notes, and snippets.

@danielboggs
Last active December 24, 2015 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danielboggs/6773673 to your computer and use it in GitHub Desktop.
Save danielboggs/6773673 to your computer and use it in GitHub Desktop.
Rails app error messages helper... allows <%= f.error_messages %> in form_for blocks.
module ErrorMessagesHelper
# Render error messages for the given objects. The :message and :header_message options are allowed.
def error_messages_for(*objects)
options = objects.extract_options!
# options[:header_message] ||= I18n.t(:"activerecord.errors.header", :default => "Invalid Fields")
# options[:message] ||= I18n.t(:"activerecord.errors.message", :default => "Correct the following errors and try again.")
messages = objects.compact.map { |o| o.errors.full_messages }.flatten
unless messages.empty?
content_tag(:div, :class => "message message--error") do
list_items = messages.map { |msg| content_tag(:li, msg) }
content_tag(:ul, list_items.join.html_safe)
end
end
end
module FormBuilderAdditions
def error_messages(options = {})
@template.error_messages_for(@object, options)
end
end
end
ActionView::Helpers::FormBuilder.send(:include, ErrorMessagesHelper::FormBuilderAdditions)
@leonardofaria
Copy link

I just updated the code to works fine in Rails 4
https://gist.github.com/leonardofaria/bf88d8fb1e5cf1fd2a0b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment