开发者

Why does my flash[:notice] appear permanently on the redirected page? - Rails 3.1

开发者 https://www.devze.com 2023-04-11 21:37 出处:网络
Why does my flash[:notice] appear permanently on the redirected page? - Rails 3.1 In my ApplicationController I have this before_filter:

Why does my flash[:notice] appear permanently on the redirected page? - Rails 3.1

In my ApplicationController I have this before_filter:

before_filter   :expire_session

def expire_session
  if session
    reset_session if session[:last_seen] < 15.minutes.ago
    flash[:error] = "Your session has timed out. Please log back in."
    session[:last_seen] = Time.now
  end
end

In my sessions_controller, these are the error and destroy actions:

  def error
    flash[:error] = "We're sorry. You need to sign in to get access to that page."
    redirect_to root_path
  end

  def destroy
    reset_session
    redirect_to root_path, :notice => "Signed out!"
  end

It works perfectly, i.e. it expires my session after X minutes of inactivity - which is what I want. The issue is, when it redirects me to the root_path, it has this message:

Your session has timed out. Please log back in.

If I reload the page, the message is still there. If I close the tab and come back to that URL, that message is still there.

The other messages generated in flash[:notice] or flash[:error] display only once and when you reload the page, they are开发者_运维问答 gone.

Why is this one sticking around?

Thanks.


Try to rewrite expire method:

before_filter   :expire_session

def expire_session
  if session && session[:last_seen] < 15.minutes.ago
    reset_session
    flash[:error] = "Your session has timed out. Please log back in."
  elsif session
    session[:last_seen] = Time.now
  end
end


You are not splitting on the condition, so you are setting the flash every request. You can fix it like this:

def expire_session
  return unless session

  if session[:last_seen] < 15.minutes.ago
    session[:last_seen] = Time.now
  else
    reset_session
    flash[:error] = "Your session has timed out. Please log back in."
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号