Rails flash hash for same request

In my very first project with Ruby on Rails several months ago I almost freaked out finding a better way for displaying a flash message for the same request and rendering an action instead of redirecting it elsewhere.

For those who are not aware about the flash message concept of Rails framework. There are times when we wish to show message to the user after processing his request say for an example if the user had entered incorrect username or password then we tell him ‘The entered username or password is incorrect please try again‘. So we just need to assign our "cool" message to a key in flash hash like flash[:notice] = "my really cool message" and in our layout that we use for our application we keep a place to display the message stored in flash[:notice].

In Rails there are two things render and redirect, redirect does as it sounds, it redirects the current request to some another action and render uses the same request and executes a different action instead of the one it was intended for or the one intended in a case where there is no redirect or render.

The flash hash is volatile in nature and its default implementation is intended to be used with redirect. As soon as the next request is served the flash hash is flushed and so is the message stored in flash[:notice] is gone.

Now in a case where we use redirect like if we do the authentication in login action and lets application render the login action in the same request authentication took place. The message will be displayed if the authentication failed else we would redirect the user to his secret place having passed the authentication. But after a failed authentication request the message is not gone as a new request was not being served using redirect. Now if the user passes the authentication he will be taken to his secret place but the message is being retained in notice key of flash hash as it is being designed to, same will be the case if users navigates to some another part of application by clicking some link. Our "cool" message will be shown to the user in his secret place or any where he may go on his next request. Ouch that is what we were not willing to do.

So the solution for this is to assign our "cool" message to flash.now[:notice] instead of flash[:notice] well sounds quite obvious, isn’t Rails framework very human friendly. Using flash.now[:notice] will not retain the message for next request and flash[:notice] will have the message preserved for the current request it wont be available there after.

Rails Documentation of Flash Hash

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>