Rolling Windows and Sticky Bytes

<tagline type="clever"/>

flash and flash.now

on 2012-08-13

Are the flash messages in your Ruby on Rails application persisting through multiple pages in strange and exciting ways or failing to appear completely?

If so, you may be confusing flash[:warning] = "Some Message" with flash.now[:warning] = "Some Message"!

The key difference is that flash will persist to the next request before being cleared, where flash.now only persists until the end of the current request.

In practice, this means that your controller methods should use flash if your exit point is a redirect (since a new request will be created following the redirect) and should use flash.now if your exit point is a render (since flash.now will be presented to the user during the natural lifespan of the current request, then cleared).

Render — Wrong Way (flash will persist too long):

if song.valid?
  flash[:notice] = "Song saved successfully."
else
  flash[:warning] = "Unable to save song."
end
render :edit_song

Render — Right Way:

if song.valid?
  flash.now[:notice] = "Song saved successfully."
else
  flash.now[:warning] = "Unable to save song."
end
render :edit_song

Redirect — Wrong Way (flash will not appear):

if song.valid?
  flash.now[:notice] = "Song saved successfully."
else
  flash.now[:warning] = "Unable to save song."
end
redirect songs_url

Redirect — Right Way:

if song.valid?
  flash[:notice] = "Song saved successfully."
else
  flash[:warning] = "Unable to save song."
end
redirect songs_url

References: http://stackoverflow.com/questions/4613952/why-flash-message-wont-disappear


Leave a Reply

Your email address will not be published. Required fields are marked *