Syndication IconNew article alerts are available via Atom. Hide this message

Showing multiple message types with the flash

Traditionally the Rails flash is used to store only one message, usually in flash[:message] but I like to be able to differentiate between warnings and information in my view rather than displaying them both in the same place in the same style.

The flash is a HashWithIndifferentAccess so we can use any key we want to store messages and pull them back out later, in the view.

In your controller you simply use whichever key is most appropriate.

if @widget.save
  flash[:info] = "Your widget has been saved."
  flash[:notice] = "There are now #{Widget.count} widgets."
  redirect_to @widget and return
else
  flash.now[:warning] = "I couldn't save your widget."
  render :action => "edit"
end

In the view you can now iterate over the flash and pick out the key and the message.

<%= flash.sort.collect do |level, message|
  content_tag(:p, message, :class => "flash #{level}", :id => "flash_#{level}")
end.join %>

Say the @widget got saved earlier, you'd end up with some easily understood and styled markup.

<p class="flash info" id="flash_info">Your widget has been saved.</p>
<p class="flash notice" id="flash_notice">There are now 29 widgets.</p>

Of course, in the interest of readability the flash loop in the view should be extracted to a helper, but that's left as an exercise for the reader.

Related articles

Commenting is closed for this article.

About the author

A picture of Craig in black and white

Hi, I'm Craig. I'm obsessed with the web, accessibility, usability and good design in general. I live, work and play in London and love it.

Occasionally I have to work. When I do I generally use Ruby — frequently Rails. I'm available for freelance work if you have an interesting project.

You can contact me by email, MSN or GTalk / Jabber. My address on all of these is craig@xeriom.net.

I Work With Rails

Recommend Me

Blog Roll

Now Playing