before_filter语法,当你想要“除”控制器“abc”

时间:2012-02-20 20:18:27

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

在Rails中,当你想要“除”控制器“abc”时,什么是before_filter语法。

示例,在application_controller中,如果我想说:

before_filter :login_required :except => ["-name of controller-"]

背景 - 只需要整个应用程序的基本身份验证,除了实际处理用户身份验证的控制器....

3 个答案:

答案 0 :(得分:57)

您可以将以下行放在不应执行before_filter的控制器中:

skip_before_filter :login_required

您甚至可以使用before_filter:only选项指定忽略:except的方法:

skip_before_filter :login_required, :only => [:login]

示例here


修改:使用Rails 4,before_filterbefore_action别名,skip_before_filter也与skip_before_action别名

答案 1 :(得分:14)

before_filter语法是

before_filter :login_required, :except => ["-name of the action-"]

查看Rails API Doc

答案 2 :(得分:3)

我建议不要使用控制器名称,而应该利用控制器从父级继承过滤器这一事实。所以我推荐的是这样的:

# app/controllers/application_controller.rb
class ApplicationController
  # no filters here
end

# app/controllers/authenticated_controller.rb
class AuthenticatedController < ApplicationController
  before_filter :login_required
end

# app/controllers/some_other_controller.rb
class SomeOtherController < AuthenticatedController
  # inherits the before_filter from AuthenticatedController
  # use this for most of your other controllers
end

# app/controllers/unauthenticated_controller.rb
class UnauthenticatedController < ApplicationController
  # no filters, since this inherits directly from ApplicationController
  # use this for the controller that you don't want to check login on
end

这意味着控制器知道他们是否应该检查登录,而不是拥有(可能是脆弱的)名单。