登录 主页

Render and/or redirect were called multiple times in this action……you need to do something like "redirect_to(...) and return"

2023-08-19 10:16AM

代码如下: 创建一个用户登录

 def  login
  6     login = params[:login]
  7     password = params[:password]
  8     
  9     user = User.where('login = ?', login).last
 10     # 如果用户存在
 11     if user.present?
 12   
 13       # 判断密码是否正确
 14       if user.password == password
 15       
 16         # 当前用户是正确登录的
 17         session[:current_user] = user
 18         session[:is_user_login] = '管理员登录了!'
 19         
 20       
 21         Rails.logger.info "=== '登录成功'"
 22         redirect_to '/articles'
 23       else
 24         Rails.logger.info "=== 用户名对,密码不对"
 25       end
 26     else  
 27       Rails.logger.info "=== '用户名不对'"
 28     end   
 29           
 30    Rails.logger.info "=== '用户名与密码不匹配'"
 31    redirect_to :back, notice: '用户名与密码不匹配'
 32   end

然后再浏览器运行的时候报错:在此操作中多次调用渲染和/或重定向……?

AbstractController::DoubleRenderError in UsersController#login

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

30    Rails.logger.info "=== '用户名与密码不匹配'"
 31    redirect_to :back, notice: '用户名与密码不匹配'
 32   end

 解决方法:在22行后面加上 and return,就可以了

 21         Rails.logger.info "=== '登录成功'"
 22         redirect_to '/articles' and return
 23       else
 24         Rails.logger.info "=== 用户名对,密码不对"
 25       end

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论