61

为了清楚起见,名称和对象已被简化。基本概念保持不变。

我有三个控制器:dogcathorse。这些控制器都继承自控制器animal。在控制器animal中,我有一个 before 过滤器,用于对用户进行身份验证:

before_filter :authenticate

def authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == "foo" && password == "bar"
  end
end

show操作中dog,我需要对所有用户开放访问(跳过身份验证)。

如果我要单独为 编写身份验证dog,我可以这样做:

before_filter :authenticate, :except => :show

但由于dog继承自animal,我无权访问特定于控制器的操作。添加控制器不仅会跳过对 的动作的认证:except => :show,还会跳过和的动作。这种行为是不希望的。animalshowdogcathorse

我如何才能跳过身份验证仅用于同时仍继承自的show操作?doganimal

4

4 回答 4

112
class Dog < Animal
  skip_before_filter :authenticate, :only => :show
end

有关过滤器和继承的更多信息,请参阅ActionController::Filters::ClassMethods

于 2010-03-05T21:57:09.730 回答
12

给出的两个答案都对了一半。为了避免打开所有的狗动作,您需要限定 skip_before_filter 仅适用于“显示”动作,如下所示:

class Dog < Animal
  skip_before_filter :authenticate, :only => :show
end
于 2011-04-01T02:07:49.263 回答
3

为此,您可以使用 skip_before_filter

Rails API中对此进行了解释

在你的例子dog中只需要包含

skip_before_filter :authenticate
于 2010-03-05T21:55:21.200 回答
3

只是使用 rails 4 的一个小更新,现在skip_before_action :authenticate, :only => :show应该使用 before_filters before_action

于 2014-12-09T19:08:58.730 回答