0

認証に関する railscast のチュートリアルに従いました。認証する必要がある 2 つのモデルがあるため、セッション作成コードを少し変更しました。

 def create
   if User.find_by_username(params[:username]) != nil
     user = User.find_by_username(params[:username])
     if user && user.authenticate(params[:password])
       session[:user_id] = user.id
       redirect_to root_path, notice: "Eingeloged als User"
     end
   elsif Admin.find_by_username(params[:username]) != nil
     admin = Admin.find_by_username(params[:username])
     if admin && admin.authenticate(params[:password])
       session[:user_id] = admin.id
       redirect_to adminpage_index_path, notice: "Eingeloged als Admin"
     end
   else   
     flash[:error] = "Benutzername oder Password ist falsch"
     render 'new'
   end
 end

ユーザーとしてログインすると機能し、偽のパスワードを入力すると機能します。しかし、どういうわけか、管理者としてログインしたいときにエラーが発生します:

Template is missing
Missing template sessions/create

このエラーが発生する理由がわかりません。私のコードは、セッションの作成にリダイレクトする必要があると言っていますか? ありがとう

私のルート:

get 'login', to: 'sessions#new', as: 'login'
get 'logout', to: 'sessions#destroy', as: 'logout'

resources :users
resources :sessions
4

3 に答える 3

0

コントローラー アクションのロジックを見てください。

if admin && admin.authenticate(params[:password])
  session[:user_id] = admin.id
  redirect_to adminpage_index_path, notice: "Eingeloged als Admin"
end

有効なユーザー名と無効なパスワードを入力した場合、どうなりますか?

そのステートメントに入るつもりはありませんif-コントローラーアクションを続行し、一番下に落ちます.Railsのデフォルトの動作は、他の動作が要求されていない場合、アクションの最後にビューをレンダリングすることです. . したがって、作成アクションの作成ビューをレンダリングしようとしていますが、これは存在しません。

ユーザーと管理者の両方の無効なパスワードのケースを処理する必要があります。

find_by_usernameまた、ユーザーと管理者の両方に 2 回電話をかけているのはなぜですか?

于 2013-10-18T13:54:54.983 に答える
0

管理者認証のelse部分が欠落していると思います..そうあるべきです、

def create
   if User.find_by_username(params[:username]) != nil
     user = User.find_by_username(params[:username])
     if user && user.authenticate(params[:password])
       session[:user_id] = user.id
       redirect_to root_path, notice: "Eingeloged als User"
     else
       redirect_to root_path, notice: "Your Notice"
     end
   elsif Admin.find_by_username(params[:username]) != nil
     admin = Admin.find_by_username(params[:username])
     if admin && admin.authenticate(params[:password])
       session[:user_id] = admin.id
       redirect_to adminpage_index_path, notice: "Eingeloged als Admin"
     else
       redirect_to root_path, notice: "Your Notice"
     end
   else   
     flash[:error] = "Benutzername oder Password ist falsch"
     render 'new'
   end
 end
于 2013-10-18T13:49:30.653 に答える
0

したがって、障害のある行はのようredirect_to adminpage_index_path, notice: "Eingeloged als Admin"です。ルートを投稿すると役立つ場合があります(rake routesターミナルから実行します)。テンプレートが見つからないと言っている場合は、おそらく app/views/adminpages/ フォルダーに index.html.erb がありませんか? そこにファイルはありますか?(また、適切な app/contollers/adminpages_controller と適切なindexアクションがあることを確認してください。

于 2013-10-18T13:51:19.900 に答える