Showing multiple message types with the flash

December 15, 2007 · 1 min read

Most Rails developers use the flash to store a single message -- something like `flash[:message]` -- and call it a day. But what if you want to tell a user their widget was saved *and* give them a heads-up that they're approaching a limit? Lumping everything into one message with one style isn't great. Good news: the flash is a `HashWithIndifferentAccess`, which means you can use whatever keys you like. Let's put that to work. In your controller, just pick the key that best describes what you're communicating: ```ruby 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 ``` Then in your view, iterate over the flash and render each message with its own class: ```ruby <%= flash.sort.collect do |level, message| content_tag(:p, message, :class => "flash #{level}", :id => "flash_#{level}") end.join %> ``` If that `@widget` was saved successfully, you'd get clean, easily styled markup: ```html

Your widget has been saved.

There are now 29 widgets.

``` Each message type gets its own CSS class, so you can style warnings differently from informational notices. A little CSS and your users will always know exactly what kind of feedback they're getting. In the interest of readability, that flash loop in the view really ought to be extracted into a helper -- but I'll leave that as an exercise for the reader.

These posts are LLM-aided. Backbone, original writing, and structure by Craig. Research and editing by Craig + LLM. Proof-reading by Craig.