Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the flash hash to persist through redirects

My basic use case is do some processing, set flash[:notice], and then redirect to a new page. From what I can tell, redirects reset the flash tag (please correct me if I'm wrong). Is there a way to gain persistence? Using sessions isn't an option, and I have hacked around the problem using cookies, but I think there's got to be a better way.

like image 371
Samantha Bennett Avatar asked Oct 16 '09 19:10

Samantha Bennett


2 Answers

The flash hash persists for exactly one redirect or render. So you should be fine with the default settings.

If you need to keep the flash hash for another request/redirect, you can call flash.keep.

flash.keep # keep the entire flash hash around for an extra request. flash.keep(:notice) # keep just flash[:notice] for an extra request. 
like image 155
EmFi Avatar answered Oct 01 '22 16:10

EmFi


Something to be aware of in at least Rails v3.2.1 is that the flash will persist through a redirect if its not referenced at all through at least 1 redirect and load the same view after. This is a pseudo code of my recent experience:

def some_action  (code that may set a flag to redirect 1 time)  redirect_to action_path if(redirect_flag) .... end 

Running this would result in the flash[:message] being present regardless of the redirect.

def some_action logger.debug("Flash[:message] #{flash[:message]}")  (code that may set a flag to redirect 1 time) redirect_to action_path if(redirect_flag) .... end 

During debugging with the logger referencing flash[] it would only show up when the redirect didn't happen. I could see this being problematic if you added a reference to flash before a redirect and lost it down the line for no apparent reason.

See ruby docs here (Instance protected method: Use at the bottom)

like image 26
sirclesam Avatar answered Oct 01 '22 18:10

sirclesam