2012-02-20 17 views
27

在Rails中當你想要「除」控制器「abc」時,before_filter語法是什麼。before_filter語法當你想「除」控制器「abc」

例,在application_controller如果我想說:

before_filter :login_required :except => ["-name of controller-"] 

背景 - 只是想跨除了實際處理得到一個用戶認證的控制整個應用程序的基本認證....

回答

55

你可以把控制器以下行,其中before_filter不應該被執行:

skip_before_filter :login_required 

你甚至可以specifiy其中before_filter:only:except選項忽略方法:

skip_before_filter :login_required, :only => [:login] 

一個例子here


編輯:使用Rails 4,before_filter的別名與before_action,並skip_before_filter也用別名skip_before_action

14

before_filter語法

before_filter :login_required, :except => ["-name of the action-"] 

Rails API Doc看看。

3

而不是使用控制器的名稱,我建議利用控制器繼承他們的父母的過濾器的事實的優勢。那麼我建議是這樣的:

# app/controllers/application_controller.rb 
class ApplicationController 
    # no filters here 
end 

# app/controllers/authenticated_controller.rb 
class AuthenticatedController < ApplicationController 
    before_filter :login_required 
end 

# app/controllers/some_other_controller.rb 
class SomeOtherController < AuthenticatedController 
    # inherits the before_filter from AuthenticatedController 
    # use this for most of your other controllers 
end 

# app/controllers/unauthenticated_controller.rb 
class UnauthenticatedController < ApplicationController 
    # no filters, since this inherits directly from ApplicationController 
    # use this for the controller that you don't want to check login on 
end 

這意味着控制器知道他們是否會應該檢查登錄,而不是名稱的(可能是脆的)名單。