0

我遵循了 railscast 关于身份验证的教程。因为我有两个需要验证的模型,所以我稍微更改了会话创建代码:

 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

Look at the logic in your controller action:

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

If you have provided a valid username and an invalid password, what is going to happen?

You're not going to get into that if statement - you're going to continue through the controller action, fall out the bottom, and the default behaviour in Rails is to render a view at the end of an action if no other behaviour is requested. Hence it's trying to render the create view for your create action - which doesn't exist.

You need to handle the invalid-password case for both users and admins.

Also, why are you calling find_by_username twice for both users and admins?

于 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 回答