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 => :show在animal控制器不仅将跳过认证show的作用dog,也表明中cat和horse.不希望出现这种情况.
如何才能跳过身份验证仅针对仍然继承的show操作?doganimal
Jim*_*dra 111
class Dog < Animal
skip_before_filter :authenticate, :only => :show
end
Run Code Online (Sandbox Code Playgroud)
有关过滤器和继承的更多信息,请参阅ActionController :: Filters :: ClassMethods.
rig*_*gyt 12
给出的两个答案是对的.为了避免让你的所有狗行动都开放,你需要使skip_before_filter符合以下条件:仅适用于'show'动作,如下所示:
class Dog < Animal
skip_before_filter :authenticate, :only => :show
end
Run Code Online (Sandbox Code Playgroud)