2011-05-17 61 views
10

我使用Devise的內置before_filter :authenticate_user!。我想在我的應用程序助手中調用我自己的自定義方法,如果用戶未能使用before過濾器(嘗試在註銷時執行操作)。如何以及在哪裏可以做到這一點?before_filter與設計

+0

你看看使用CanCan進行授權。 – 2011-05-17 17:11:36

回答

6

我會在使用user_signed_in?的過濾器之前編寫自定義。這隻會返回一個布爾值,而不會執行任何authenticate_user!所做的重定向類型的操作。

所以,你可以像這樣的過濾器之前寫:

before_filter :custom_user_auth 
... 
def custom_user_auth 
    unless user_signed_in? 
     # Do custom stuff, ultimately restricting access to the 
     # ...protected resource if it needs to be 
    end 
end 

請注意,這個過濾器之前不會保護你的資源從未經授權的用戶,除非該unless語句的內部區域重定向或渲染。

+0

可以將該方法放入我的應用程序控制器嗎? – user730569 2011-05-17 17:21:39

+0

如果您打算在多個控制器中使用before過濾器,每個控制器都擴展ApplicationController,那麼我會在那裏定義函數。然而,我絕對不會把'before_filter'這行放在應用程序控制器中,因爲你可能只想在某些情況下使用它。 – andrewmitchell 2011-05-17 17:24:13

7

而不是調用before_filter :authenticate_user!在你的控制器寫你自己的函數,調用authenticate_user!。例如:

before_filter :logged_in 

... 

private 
def logged_in 
    your_function 
    authenticate_user! 
end