ruby-on-railsrails-flash

Rails Flash doesn't behave as what the Rails Guide says


According to the official flash section on Rails Guide:

The Flash

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.

...

flash.now

By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request.

However, after doing some test, I found that flash is available in the current & next request. And flash.now is only available in the current request.

Is the Rails Guide incorrect? Or maybe I miss something?

# Controller action
def test_flash
  flash[:notice] = "This is a flash msg."
end

# test_flash.html.erb
<% flash.each do |name, msg| -%>
  <%= content_tag :div, msg, class: name %>
<% end -%>

Solution

  • I won't say the document is incorrect, but I agree it could be more clear. It should be phrased something like:

    Flash is clear after next request, therefore it's available in the current request and next request. If you only want it be available in the current request, not along with the next request, use flash.now.

    On the other hand, don't you think something is not available in the current request, given current flash API, as a hash like object, it would be quite weird? For example:

    flash[:notice] = 'nnf'
    puts flash[:notice] # => nil
    

    It would make more sense with write and read if that's the case.