Ruby-on-rails 在 Rails 中跳过 before_filter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2390178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Skip before_filter in Rails
提问by Yuval Karmi
Names and objects have been simplified for clarity's sake. The basic concept remains the same.
为清楚起见,名称和对象已被简化。基本概念保持不变。
I have three controllers: dog, cat, and horse.
These controllers all inherit from the controller animal.
In the controller animal, I have a before filter that authenticates a user as such:
我有三个控制器: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
In the showaction of dog, I need to have open access to all users (skip the authentication).
在show操作中dog,我需要对所有用户开放访问(跳过身份验证)。
If I were to write the authentication separately for dog, I could do something like this:
如果我要为 单独编写身份验证dog,我可以这样做:
before_filter :authenticate, :except => :show
But since doginherits from animal, I do not have access to the controller-specific actions. Adding :except => :showin the animalcontroller will not only skip authentication for the showaction of dog, but also that of catand horse. This behaviour is not desired.
但是由于dog继承自animal,我无权访问特定于控制器的操作。添加:except => :show在animal控制器不仅将跳过认证show的作用dog,也表明中cat和horse。这种行为是不希望的。
How can I skip the authentication only for the showaction of dogwhile still inheriting from animal?
我怎样才能跳过仅对仍然继承自的show操作的身份验证?doganimal
回答by Jimmy Cuadra
class Dog < Animal
skip_before_filter :authenticate, :only => :show
end
See ActionController::Filters::ClassMethodsfor more info on filters and inheritance.
有关过滤器和继承的更多信息,请参阅ActionController::Filters::ClassMethods。
回答by rigyt
The two answers given are half right. In order to avoid making all your dog actions open, you need to qualify the skip_before_filter to only apply to the 'show' action as follows:
给出的两个答案都对了一半。为了避免打开所有 dog 动作,您需要限定 skip_before_filter 仅适用于“show”动作,如下所示:
class Dog < Animal
skip_before_filter :authenticate, :only => :show
end
回答by Thresh
Just a small update that using rails 4, it is now skip_before_action :authenticate, :only => :showand that before_filters should now use before_actioninstead.
只是使用 rails 4 的一个小更新,现在skip_before_action :authenticate, :only => :show应该使用 before_filters before_action。
回答by ajmurmann
For this you can use skip_before_filter
为此,您可以使用 skip_before_filter
It's explained in the Rails API
它在Rails API 中有解释
In your example dogjust would have to contain
在你的例子中dog只需要包含
skip_before_filter :authenticate

