Preserving Data Stored in the Rails Flash

Hypertext Transfer Protocol (HTTP) is the data communication protocol for the World Wide Web; it defines how a client (web browser) communicates with a web server.

The Limitation of HTTP

HTTP is a stateless protocol — meaning that information communicated between the client and the server is not preserved between requests. This poses a challenge for web applications that need to remember information about an end-user. For example, when an user places a product in her virtual shopping cart on, the product should remain in her shopping cart until she's ready to checkout. Products in her shopping cart should not be lost when she navigates to a different page to view another product.

The Rails Flash

As one solution to overcome the stateless limitation of HTTP, most web application frameworks — Ruby on Rails included — implement what is referred to as a session. The session allows data associated with an user to persist over multiple requests.

In addition to the session, Rails provides an object called the flash. Whereas the session persists data over multiple requests, data stored in the flash is only kept around for one request.

One of the most common uses of the flash is to store a message in the controller layer that is accessed from the view layer to relay information to the end-user.

The message is stored in the flash prior to performing a redirect in the controller:

flash[:notice] = "Product added to shopping cart"
redirect_to root_path

In the view, the message is displayed using HTML markup:

<%= flash[:notice] %>

The message is discarded after the view is rendered.

Preserving Data in the Flash Hash for More Than One Request

There are times — albeit rare — when it's necessary to keep data stored in the flash around for an additional request. In these cases, the flash provides a method called keep:

def create
  flash[:notice] = "Keep this message around"
  redirect_to action: :index

def index
  redirect_to action: :somewhere_else

def somewhere_else

In this example, data will remain in the flash for two requests (two redirects), allowing the view for the somewhere_else action to render the message that was stored in the flash in the create action.

Bonus Tip

The Rails flash also provides a method called discard. As you may have guessed, it is used to remove data from the flash.

Additional Reading

Take a look at the Rails API documentation for more details on the flash here.