Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flash message persists on reload

I have simple actions that look like this:

def edit_password
end

def update_password
  if @user.update(user_params)
    redirect_to @user, notice: "Password was successfully changed"
  else
    flash.now[:notice] = "Password not changed"
    render :edit_password
  end
end

In my view I have:

<% if flash[:error] 
  <%=flash[:error] %>
<% end %>

The flash message is displayed correctly (when the password is not changed). But when I reload the page, the message persists. I believe that it should go away on a page refresh. What am I doing wrong? I have looked everywhere and this seems so simple, but I can't figure it out. Appreciate any help.

like image 632
RajeshM Avatar asked Nov 10 '22 02:11

RajeshM


1 Answers

I was having the same issue and here is what I did to get around it. I created the following method in action_controller and call it as a before_action filter from my other controllers where needed:

def clear_flash_messages
  flash[:notice] = nil
  flash['danger'] = nil
  flash['success'] = nil
  flash[:warning] = nil
end

This will effectively clear any stale flash messages and would allow you to start new regardless of if you're simply reloading or redirecting.

like image 143
Andrea Avatar answered Nov 14 '22 22:11

Andrea