2013-01-15 23 views
0

在application_controller.rb我有以下:导轨skip_before_filter方法中(其他before_filters已经运行之后)

before_filter :get_events 
before_filter :get_sitemap 
def login_required 
    return true if session[:user] 
    # If we get to this point, I want to avoid running get_events and get_sitemap 
    flash[:warning] = 'Please login to continue' 
    redirect_to login_users_url 
    return false 
end 

而在其他控制器我有例如:

before_filter :login_required, :except => [:show] 

所以基本上我有运行方法访问数据库的所有页面,除了我不希望它发生在用户需要登录时(即,从通常需要get_events和get_sitemap的页面重定向)。

我认识到这样做的一种方法是,在设置任何其他before_filters之前,在所有控制器上运行login_required作为before_filter,然后排除某些控制器模型,但我想知道是否有办法做到这一点,而无需改变我的所有控制器。

回答

0

考虑到约书亚的回答,我仍然无法得到我想要去的......所以我做的是做一个小混合解决方案。所有的控制器仍然引用ApplicationController,但是在ApplicationController中,我总是在其他before_filters之前运行before_filter :login_required FIRST。重定向轨道似乎阻止其他before_filters运行,这是我想要的。在其他控制器中,我会根据需要使用skip_before_filter :login_required, :only => [:this_time]

+0

究竟:only => [:this_time]选项是做什么的? – Ameen

+0

:this_time不是一个真正的方法;我只是把它写成'伪代码'。您可以使用控制器操作的方法名称来跳过登录...... so [:create,:update ...]等等等等。 – JakeTheSnake

4

这样的事情,我通常会创建一个AuthenticatedController(在应用程序/控制器/ authenticated_controller.rb):

class AuthenticatedController < ApplicationController 

    before_filter :require_login 

end 

然后我需要获得来自该认证的所有控制器,用于指定动作skip_before_filter :require_login我想排除在控制器之上。例如:

class PlanetsController < AuthenticatedController 

    skip_before_filter :require_login, only: [:index] 

end 

这将要求您更改所有控制器,但只从AuthenticatedController推导的目的。据我所知这是一个完全可以接受的方式来处理它,我不认为有一种方法可以解决猴子补丁ActionController :: Base的问题,它可以适用于所有的控制器,这对于各种各样的原因。

+0

我该怎么做?我试过类AuthenticationController JakeTheSnake

+0

你把它放在文件app/controllers/authentication_controller.rb? –

+0

用示例代码更新了我的答案。 –

相关问题