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.

written by
Craig
published
2007-12-15
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO http://barkingiguana.com/2007/12/15/showing-multiple-message-types-with-the-flash.html.orig
curl -LO http://barkingiguana.com/2007/12/15/showing-multiple-message-types-with-the-flash.html.orig.asc
gpg --verify showing-multiple-message-types-with-the-flash.html.orig{.asc,}