2011-12-15 33 views
4

我有一個current_user方法來處理身份驗證。找不到id = 1的用戶

application_controller.rb

protect_from_forgery 
helper_method :current_user 

def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
end 

,但是當我嘗試存取權限一個一個網頁,我得到了以下錯誤:

Couldn't find User with id=1 
app/controllers/application_controller.rb:10:in `current_user' 

如何傳遞@current_user一種默認值,所以如果沒有用戶,它將重定向到登錄頁面。

感謝您的幫助。

回答

12

它看起來像你的會話包含舊數據,特別是不再存在的用戶的id(1)。嘗試處理RecordNotFound例外通過ActiveRecord的提高,並返回nil:

def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    rescue ActiveRecord::RecordNotFound 
end 

要重定向,您應該添加第二個before_filter這將檢查用戶並處理重定向到登錄路徑:

before_filter :require_user 

def require_user 
    redirect_to login_path unless current_user 
end 

記住通過將skip_before_filter :require_login添加到哪個控制器管理您的身份驗證來省略登錄操作require_user

+0

Thans for helping.I guess that old data was from a migration mess I've reset reset migration multiple。 – 2011-12-15 21:41:33