2010-03-05 169 views
57

爲了清楚起見,名稱和對象已被簡化。基本概念保持不變。在rails中跳過before_filter

我有三個控制器:dog,cathorse。這些控制器全部從控制器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 

但由於從animaldog繼承,我沒有訪問控制器專用的行動。在animal控制器中添加:except => :show將不僅跳過dogshow動作的驗證,還跳過cathorse的驗證。這種行爲是不希望的。

如何跳過show動作dog而僅繼續從animal繼承認證?

回答

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

ActionController::Filters::ClassMethods更多的信息上的過濾器和遺產。

+2

'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'。 – Bachet 2011-05-06 20:34:56

+4

不是..他們只是將該方法移動到另一個類,http://apidock.com/rails/v3.2.3/AbstractController/Callbacks/ClassMethods/skip_before_filter – Orlando 2012-06-05 13:54:19

+0

是的,它已被移動 – 2014-05-06 05:46:20

3

爲此,您可以使用skip_before_filter

它在Rails API

解釋在您的例子dog只是必須包含

skip_before_filter :authenticate 
12

給出的兩個答案是一半的權利。爲了避免讓你的所有的狗動作打開,你需要限定skip_before_filter只適用於「顯示」行動如下:

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

只是,使用軌道4小的更新,現在是skip_before_action :authenticate, :only => :show和before_filters現在應該使用before_action來代替。

+0

這應該是一個評論。 – dan 2017-08-17 14:49:48