Rails flash message remains for two page loads

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

There are two ways to solve this problem:

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

Solution 2 - Ruby on-Rails

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].

Solution 3 - Ruby on-Rails

Or you can just call the action like this

flash.now[:notice] = "Sorry, we weren't able to log you in with those details."
render 'new' #or render :new

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul FarnellView Question on Stackoverflow
Solution 1 - Ruby on-RailsSimone CarlettiView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPaul FarnellView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAnkit WadhwanaView Answer on Stackoverflow