#18 Looping Through Flash
Apr 13, 2007 | 1 minute |
Views
Displaying flash messages in the layout can be a pain at times. In this episode you will learn an easy way to display any kind of flash message by looping through the hash.
- Download:
- mp4Full Size H.264 Video (3.13 MB)
- m4vSmaller H.264 Video (2.29 MB)
- webmFull Size VP8 Video (5.69 MB)
- ogvFull Size Theora Video (4.26 MB)
This is fine approach, but it will display errors mixed with warnings in no particular order, and that is not good in my opinion. I prefer messages sorted in order of decreasing severity: [:error, :warning, :notice, :message]
I have some code that does it, but I written it at the very beginning of studying ruby/rails, so I will not posit it here, it is not pretty ;)
How about this: http://pastie.caboo.se/81153
Here's a HAML version: http://pastie.textmate.org/143587
Does anyone have the problem where the flash message stays on the page one reload more than it is supposed to?
So if you reload the page, the flash message is still there, but it goes away after a second reload.
Its a problem because if you carry out an action and you get an error, then do it again and get a success message, the previous message is displayed on the page at the same time as the current one.
@austin_web_developer You can fix this by using flash.now[:notice] instead of flash[:notice]. I wrote a blog post explaining how the flash hash works: http://travisonrails.com/2008/08/17/Working-with-the-flash-hash"
Having trouble with flash.. with flash[:notice] or the method shown here, any use of flash causes a 'stack level too deep' error. Is there any way to clear the flash ? I assume this would clear the error.
Bob
A very good article, I will always come in.
I'm new to Rails. Love the RailsCasts. Sometimes, even using the Flash.now, I get a one-line blank highlighted line on the next page, reached by using a Nav bar link_to function. The idea is that sometimes the user sees the error message and just bails out to another place in the program using the navigation bar function. The html source of the problem page reads:
<div id="notice"></div><div id="warning"></div>
On Safari on a Mac, this generates a single colored line for each division, containing no text.
I've only been able to eliminate this quirk by adding an "if flash[:error]" check before div & flash lines - obviously not using the cycling method described here and typing many more characters. Any tips would be appreciated.
I like it very much, hope you can have a look at my site
This episode has been updated for Rails 5 as a blog post. Looping Through Flash in Rails 5