2011-09-15 134 views
1

我想/東西只可訪問爲登錄的用戶,我有一個CURRENT_USER幫手如果當前訪問者沒有登錄,它返回一個用戶ID或零。限制某些航線登錄用戶

哪裏可以限制訪問控制器中的某些東西,或者可以將它作爲路由的一部分添加?

回答

4

您必須添加控制器:before_filter併爲此創建操作。

:before_filter :authenticate 

def authenticate 
    redirect_to(registration_path) unless current_user.nil? 
end 

此外,您可以使用:only或:除了過濾器選項。 或者我沒有明白的問題?

+0

另外,推薦給你railstutorial.org。很好的新手教程。 – avy

+0

我不得不使用'before_filter:authenticate'來使這個工作。沒有領先的冒號。 – jcollum

+0

自回答開始,它被重命名爲'before_action',正確的形式是:'before_action:authenticate'和'@ current_user.nil?',因爲這可能是一個實例變量。 – watt

3

你應該在你的控制器中處理。路線決定事情的發展方向,然後由管制員決定是否允許你去那裏。

您的ApplicationController中應該有一個通用的authenticate方法來檢查是否有人登錄並將它們重定向到登錄頁面,如果他們不是。然後在您的特定的控制器:

class SomethingController < ApplicationController 
    before_filter :authenticate 

    def handler 
    #... 
    end 
end 

您可以用:except選項中的特定處理跳過認證:

before_filter :authenticate, :except => [ :this_one, :and_this_one ] 

還有其他的選擇爲好,看到Action Controller Overview對細節的過濾器部分。