2011-12-15 16 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)が含まれているようです。 ActiveRecordのが提起したRecordNotFound例外を処理し、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

助けてください。古いデータは移行の混乱から来ていると思います。移行を複数回リセットしました。 –

関連する問題