Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Flash message persists for the next page view

I am using the following code in my layout to display two types of flash messages:

    <% if !flash[:notice].nil? %>
    <div class="row">
        <div class="flash notice col-xs-12">
            <%= flash[:notice] %>
        </div>
    </div>
    <% end %>
    <% if !flash[:error].nil? %>
    <div class="row">
        <div class="flash error col-xs-12">
            <%= flash[:error] %>
        </div>
    </div>
    <% end %>

    <%= debug(flash[:notice]) %>
    <%= debug(flash[:error]) %>

They both work fine, but whenever one is triggered, it will still appear for one additional page view. I'm not using any caching gems.

Why is this happening? And how do I fix it?

like image 202
emersonthis Avatar asked Sep 11 '13 17:09

emersonthis


1 Answers

Use flash.now instead of flash.

The flash variable is intended to be used before a redirect, and it persists on the resulting page for one request. This means that if we do not redirect, and instead simply render a page, the flash message will persist for two requests: it appears on the rendered page but is still waiting for a redirect (i.e., a second request), and thus the message will appear again if you click a link.

To avoid this weird behavior, when rendering rather than redirecting we use flash.now instead of flash.

The flash.now object is used for displaying flash messages on a rendered page. As per my assumption, if you ever find a random flash message where you do not expect it, you can resolve it by replacing flash with flash.now.

Hope that helps :)

like image 93
Rajesh Omanakuttan Avatar answered Nov 17 '22 17:11

Rajesh Omanakuttan