(void* dan)

Flash Now!

In development of a new, greenfield application I had flash messages popping up twice: once for the current page, and then again on the next page.  It turns out I was using flash[]= and then rendering within the same action.  As flash[]= is designed to carry over to the next action (i.e. after you redirect, a new action is performed) it was showing up again.  The solution: flash.now[]=.  This hash is cleared after the current action.  The following code illustrates when to use each:

def create_application
  #do work
  if it_worked?
    flash[:notice] = "Great success!"
    redirect_to @cash
  else
    flash.now[:error] = "Let's try that again"
    render :action => "new"
  end
end

The flash[:notice] must be carried over to the action that handles the @cash path (following to the redirect), whereas the flash.now[:error] will be shown for the current action (even though it renders a different view) and should not be carried over to the next action.

It seems somewhat strange to me that I’m just discovering this now.  I suppose that as I learn more about Rails and web applications in general, I adjust my techniques and start experimenting with new ones (that aren’t always better).  The fact that flash[]= carries over to the next action and flash.now[]= doesn’t has only come into play now that I’m using flash as more of a central messaging system than just the standard notices from scaffolds.


blog comments powered by Disqus
To Tumblr, Love Metalab