Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 517
Paul Farnell Avatar asked Jun 19 '09 09:06

Paul Farnell


1 Answers

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

like image 61
Simone Carletti Avatar answered Sep 16 '22 21:09

Simone Carletti