2014-02-08 21 views
0

我有一個before_filtercheck_login,看起來是這樣的:如何在rails中根路線不應用before_filter?

def check_login 
    if not session[:user_id] 
    flash[:error] = "Please log in to continue" 
    redirect_to login_path 
    end 
end 

然後我把這個before_filter在我的應用程序控制器,然後排除它在我登錄控制器(帶skip_before_filter :check_login

的問題是當用戶第一次點擊主頁(即localhost:3000)時,它會將它們重定向到顯示flash[:error]消息的登錄頁面。但是,對於主頁,我只想顯示登錄表單。處理這種「特殊情況」的最簡潔方法是什麼?我想將skip_before_filter放在處理主頁的控制器中,但我不認爲這是非常乾燥的,因爲如果我更改路線文件中的主頁,我還必須更改skip_before_filter的位置。

謝謝!

回答

0

您可以添加一個名爲action在你的主頁:

class StaticPagesController < ApplicationController 

    def home 
    end 
end 

,然後檢查你的回調當前操作:

def check_login 
    if not session[:user_id] 
    flash[:error] = "Please log in to continue" unless params[:action] == "home" 
    redirect_to login_path 
    end 
end 
1

您可以在過濾器中添加一些動作

class LoginController < ApplicationController 
    skip_before_filter :check_login, :only => [:login] 

    def login 
    end 
end 

而在應用程序控制器中,「空白?」檢查存在和無。它很有用

def check_login 
    if session[:user_id].blank? 
    flash[:error] = "Please log in to continue" 
    redirect_to login_path 
    end 
end