Rails: Flash messages doesn't clear until it is read/accessed

635 views Asked by At

I set the flash message as below in one of my routes

def signup
   flash[:is_signup] = true
   ... redirect_to route1 : route2  // based on some logic, redirect accordingly
end

def route1
    // access flash[:is_signup]
    flash.discard(:is_signup)
    // do something 
end

As depicted above, after i set the flash variable, i could redirect_to either the route(route1) that uses this flash variable or another route(route2) that doesn't care about this flash variable at all.

The issue is, when i redirect to route2, and then go on and mind my own business, hitting several routes/actions in the process, when i end up hitting the route1, the flash variable is still there.

I haven't seen anything in the documentation that says it is available until it is read. Is this the case? or am i doing something wrong?

Thanks in Advance

1

There are 1 answers

0
Brian Henry On

I'm seeing this as well (rails 4.2.11), and agree: no docs indicate access of flash should be necessary.

But, if I have a page that sets flash[:blah] = 'applesauce' and consumes the flash (e.g., puts flash[:blah]) on the next request, that key is not present in the following request. If I don't, it will linger through request after request until I hit a one where I check the flash.

My workaround is this: In application_controller.rb

class ApplicationController < ActionController::Base
  before_action :touch_flash
#...
  def touch_flash
    flash
  end
end

This act of referencing flash appears to be enough to trigger a discard at end of the request (but doesn't interfere with any actual access later in the request). Next request, it's gone as expected.