在Rails中跳过before_filter

Yuv*_*rmi 61 inheritance ruby-on-rails before-filter

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

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

before_filter :authenticate

def authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == "foo" && password == "bar"
  end
end
Run Code Online (Sandbox Code Playgroud)

show行动中dog,我需要对所有用户具有开放访问权限(跳过身份验证).

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

before_filter :authenticate, :except => :show
Run Code Online (Sandbox Code Playgroud)

但是由于dog继承自animal,我无法访问特定于控制器的操作.添加:except => :showanimal控制器不仅将跳过认证show的作用dog,也表明中cathorse.不希望出现这种情况.

如何才能跳过身份验证仅针对仍然继承的show操作?doganimal

Jim*_*dra 111

class Dog < Animal
  skip_before_filter :authenticate, :only => :show
end
Run Code Online (Sandbox Code Playgroud)

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

  • 不,不是..他们只是将方法移到另一个类,http://apidock.com/rails/v3.2.3/AbstractController/Callbacks/ClassMethods/skip_before_filter (4认同)
  • `skip_before_filter`似乎已被弃用>> [http://apidock.com/rails/ActionController/Filters/ClassMethods/skip_before_filter#1083-deprecated-moved](http://apidock.com/rails/ActionController/Filters/ClassMethods/skip_before_filter#1083-deprecated-moved)他们建议使用`skip_filter`,它一起调用`skip_before_filter`,`skip_after_filter`和`skip_around_filter`. (2认同)

rig*_*gyt 12

给出的两个答案是对的.为了避免让你的所有狗行动都开放,你需要使skip_before_filter符合以下条件:仅适用于'show'动作,如下所示:

class Dog < Animal
  skip_before_filter :authenticate, :only => :show
end
Run Code Online (Sandbox Code Playgroud)