Display error_messages_for for a single flash error using a helper

So error_messages_for has been deprecated in Rails 3. However, you can still download the plugin from here and it’s still in use in a number of projects that we come across. It’s quite often that you see flash error messages appear outside of this error messages for style box but what if you just wanted to display a standardised form across your page.
In it’s simplest form the standard error_messages_for accepts an active model object and will display all of the errors found on that object. But what if we want to just pass in the error message that it should display?

The following snippet allows you to make use of the same template used by default but accepts a string containing the error message.

  def error_from_message(error_message, options = {})
    return nil unless error_message
    
    header_message = options[:header_message] || t(:header, :count => 1, :scope => [:activerecord, :errors, :template], :model => 'item')
    message = options[:message] ||  t(:body, :scope => [:activerecord, :errors, :template])
    
    contents = ''
    contents << content_tag(options[:header_tag] || :h2, header_message)
    contents << content_tag(:p, message)
    contents << content_tag(:ul, content_tag(:li, error_message))
    content_tag(:div, contents.html_safe, :id => 'errorExplanation', :class => 'errorExplanation')
  end

If you place that into your application helper you can then call the following in the view to render the standard active model style error message for the string you supply:

<%= error_from_message flash[:error_message] %>

You can also pass some of the standard parameters to change the tag or override the default header message. There’s nothing amazing in this but hopefully it will at least show where to get started to access the standard i18n translations used by the Rails helpers.

Advertisements

About Steve Smith
Software developer (often ruby, rails but I enjoy loads of languages), semantic tech. fanboy, skydiver, all round geek. Owner of dynamic:edge (hire us) the makers of CloudMailin.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: