如何将before_filter应用于Rails 3.2.11中每个控制器的每个动作?

我想validation用户是否登录到服务器的每个请求。

就像是:

:before_filter verify_logged_in 

我应该在哪里放置before_filter,以便它适用于所有控制器操作和所有请求?

要确保filter适用于所有操作,请将其放在application_controller.rb中。

Application Controller是所有其他类的基类。

如果在此类中放置任何filter,则流程的工作方式如下:

如果您点击url说出users资源的任何操作,请说index操作然后:

控件首先转到Application Controller 。 在那里它检查filter,如果找到任何,那么它执行filter方法,然后它进入用户控制器的索引操作。

应用控制器:

 class ApplicationController < ActionController::Base protect_from_forgery before_filter :verify_logged_in end 

其他控制器:

 class UsersController < ApplicationController def index end 

在上面的代码中,您会看到另一个控制器inheritance了作为应用程序控制器的父控制器的内容。 因此,如果您将before_filter放在应用程序控制器中,那么对于每个用户,它将validation用户是否已针对每个请求登录。

将before_filter放在基类中(在application_controller.rb文件中),它将在base及其所有派生类上工作,例如

 class ApplicationController < ActionController::Base before_filter :set_locale def set_locale I18n.locale = params[:locale] or I18n.default_locale end end 

祝好运 :-)

将它放在ApplicationController并从中inheritance所有其他控制器。 如果您没有覆盖其中一个子控制器中的verify_logged_in ,它就可以正常工作。