:除非不能在应用程序控制器的before_filter中工作。路由问题? [英] :except not working in before_filter in application controller. Routing problem?

查看:110
本文介绍了:除非不能在应用程序控制器的before_filter中工作。路由问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序控制器中有一个before_filter,可以使用户会话保持活动状态(如果超时,则将其注销)。应该在除/ sessions / new和/ sessions / destroy以外的所有操作(分别以/ login和/ logout路由)上调用此操作。

I have a before_filter in my application controller to keep a user's session alive (and log them out if a time out has been reached). This should be called on every action except /sessions/new and /sessions/destroy which are routed as /login and /logout.

我的应用程序控制器的相关部分看起来像这样;

The relevant parts of my application controller look like this;

class ApplicationController < ActionController::Base
  before_filter :update_activity_time, :except => [:login, :logout]

  private

  def update_activity_time
    if current_user
      time_out = current_user.setting.remember_me ? 20160 : current_user.setting.user_timeout
      from_now = time_out.minutes.from_now
    end
    if session[:expires_at].blank?
      session[:expires_at] = from_now
    else
      time_left = (session[:expires_at].utc - Time.now.utc).to_i
      if time_left <= 0
        session_expiry
      else
        session[:expires_at] = from_now
      end
    end
  end

  def session_expiry
    reset_session
    flash[:notice] = 'Your session has expired. Please log back in.'
    unless request.xhr?
      session[:return_to] = request.request_uri
      redirect_to login_url
    else
      session[:return_to] = request.referer
      render :js => "window.location.replace(\"#{login_url}\")"
    end
  end

end

和我的route.rb包含以下内容;

and my routes.rb contains the following;

map.login "login", :controller => "sessions", :action => "new"

map.logout "logout", :controller => "sessions", :action => "destroy"

在访问/ login或/ logout时将调用before_filter。这不是停止显示,但确实会引起一些奇怪的行为(例如,从已超时的页面注销时)。

The before_filter is being called when /login or /logout are being visited. This isn't a show-stopper but it does cause a few odd behaviours (e.g. when logging out from a page that has timed out).

任何主意我是什么我做错了吗?我正在使用Rails 2.3.10。

Any ideas what I'm doing wrong? I'm using Rails 2.3.10.

推荐答案

:except 选项采用动作名称,而不是网址部分。相反,您应该执行以下操作:

The :except option takes action names, not url parts. Here's what you should do instead:

class ApplicationController < ActionController::Base
  before_filter :update_activity_time
  ...
end

然后,在 sessions_controller.rb 中:

class SessionsController < ApplicationController
  skip_before_filter :update_activity_time, :only => [:new, :destroy]
  ...
end

不想将:except 放在 ApplicationController 中,因为如果这样做,则 new每个应用程序控制器的 destroy 操作都不会更新活动时间。

You don't want to put the :except in ApplicationController because, if you did, the new and destroy actions for every one of your app's controllers wouldn't update the activity time.

这篇关于:除非不能在应用程序控制器的before_filter中工作。路由问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆