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?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With