Rails flash message remains for two page loads
I'm using a flash notice in a Rails application, with the following code:
flash[:notice] = "Sorry, we weren't able to log you in with those details."
render :action => :new
The flash message renders as expected on the 'new' action, but then it also shows on the next page the user visits (whatever that might be). It should only show once, but something's making it stick around.
There are two ways to solve this problem:
- flash.now
- flash.discard
One is to use
flash.now[:notice]
when your flash must be discarded at the end of the current request and is not intended to be used after a redirect.
The second one is to call
flash.discard(:notice)
at the end of the request.
The standard flash message is intended to be kept for the "next" request. E.g. you generate a flash while handling a create or edit request, then redirect the user to the show screen. When the browser makes the next request to the show screen, the flash is displayed.
If you actually generate a flash on the show screen itself, use flash.now
.
Check the Ruby on Rails API documentation to see how the Flash hash works
Ok, I solved this. The way to get around it is to use:
flash.now[:notice] = "Sorry, we weren't able to log you in with those details."
render :action => :new
The key part being flash.now[:notice] instead of flash[:notice].