为什么我的flash [:notice]会永久显示在重定向的页面上? - Rails 3.1

时间:2011-10-11 00:22:27

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

为什么我的flash [:notice]会永久显示在重定向的页面上? - Rails 3.1

在我的ApplicationController我有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

在我的sessions_controller中,这些是errordestroy行为:

  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

它完美运行,即它在X分钟不活动后会话到期 - 这就是我想要的。问题是,当它将我重定向到root_path时,它会显示以下消息:

Your session has timed out. Please log back in.

如果我重新加载页面,则消息仍然存在。如果我关闭标签并返回该URL,则该消息仍然存在。

flash[:notice] or flash[:error]中生成的其他消息只显示一次,当您重新加载页面时,它们就消失了。

为什么这个坚持?

感谢。

2 个答案:

答案 0 :(得分:2)

尝试重写过期方法:

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

答案 1 :(得分:1)

您没有分裂条件,因此您每次请求都要设置闪光灯。你可以像这样解决它:

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