O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.7. Maintaining the State

It is fair to state that each request-response pair is a world unto itself. For example, an instance variable set within the index action is not going to be available in the view when serving a second request for the edit action.

NOTE

By the way, go easy on the number of instance variables that you define in each action. These are expensive and introducing an excessive number of instance variables is considered to be faux pas. If a variable within a controller is not going to be used by the view, declare it as a local variable (that is, don't prefix it with a @ sign).

The stateless nature of the Web poses the challenging question of how to maintain the state. This could be something as simple as carrying a message over from an action to another when a redirect is required, or a more elaborate solution to keep track of which users are currently logged in, without prompting them to re-enter their username and password at each new request for a protected page.

In Rails, the first scenario is resolved through a flash object, and the second by employing sessions.

8.7.1. Flash

As mentioned previously, instance variables defined within an action are not available to requests that are serving a different action. The reason for this is that with each request, a brand new instance of the controller is generated. This implies that instance variables cannot be used as a means to pass messages between actions whenever you are performing a redirect (which is, for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required