This is for people coming to this question via search engines.
Problem
When the user clicks on the back button, a fresh request is not made to the server, rather the browser's cached copy is displayed. However, during the first request, the browser has already cached the flash message, and on clicking the back button, the flash message gets displayed again.
Solution
A way to get around this is to use the browser's localStorage or sessionStorage.
Change your code so that the flash messages are shown or hidden via javascript. When the flash message is shown, store that fact in the browser's sessionStorage.
Next time, check if the flash message has already been shown and if so, do not show it again.
I prefer to use sessionStorage instead of localStorage as sessionStorage gets cleaned up on closing the browser. It is helpful if you have too many flash messages. Otherwise, you will have to write the logic for removing older entries
# app/views/layouts/application.html.erb - or wherever your flash messages reside
...
<%
flash_name_mappings = {
"notice" => "success",
"error" => "danger",
"alert" => "warning"
}
%>
<% flash.each do |name, msg| %>
<% if msg.is_a?(String) %>
<% flash_token = Time.current.to_s(:number) # or use any other random token generator, like Devise.friendly_token %>
<div id="flash-<%= flash_token %>" style="display:none" class="alert alert-<%= flash_name_mappings[name] || name %>">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<%= content_tag :div, msg.html_safe, id: "flash_#{name}" %>
</div>
<script type="text/javascript">
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
if(sessionStorage["flash-<%= flash_token %>"] != "shown"){
$("#flash-<%= flash_token %>").show();
sessionStorage["flash-<%= flash_token %>"] = "shown";
}
} else {
// Sorry! No Web Storage support..
$("#flash-<%= flash_token %>").show();
}
}
</script>
<% end %>
<% end %>
...