Rails中如何跳过before_filter

61

为了简化说明,名称和对象已经被简化。基本概念保持不变。

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

before_filter :authenticate

def authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == "foo" && password == "bar"
  end
end
dogshow动作中,我需要对所有用户开放访问权限(跳过身份验证)。
如果我要单独为dog编写身份验证,我可以像这样做:
before_filter :authenticate, :except => :show

由于dog继承自animal,所以我无法访问特定于控制器的操作。在animal控制器中添加:except => :show不仅会跳过dogshow操作的身份验证,还会跳过cathorse的身份验证。这种行为是不希望的。

如何才能仅对dogshow操作跳过身份验证,同时仍然继承自animal呢?

4个回答

111

2
skip_before_filter 似乎已经被弃用 >> http://apidock.com/rails/ActionController/Filters/ClassMethods/skip_before_filter#1083-deprecated-moved 推荐使用 skip_filter,它将同时调用 skip_before_filter, skip_after_filterskip_around_filter - Bachet
4
不是说不了,只是他们把这个方法移到另一个类里了。http://apidock.com/rails/v3.2.3/AbstractController/Callbacks/ClassMethods/skip_before_filter - Orlando

12

两个答案都说对了一半。为了避免所有狗狗的操作都变成公开的,您需要限定skip_before_filter仅适用于“show”操作,具体如下:

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

3

您可以使用skip_before_filter进行此操作。

这在Rails API中有详细解释。

在您的示例中,dog只需要包含即可。

skip_before_filter :authenticate

3

这里有一个使用Rails 4的小更新:现在可以使用skip_before_action :authenticate, :only => :show来跳过身份验证,而以前的过滤器应该使用before_action代替。


这应该是一个注释。 - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接