gpt4 book ai didi

ruby-on-rails - AbstractController::DoubleRenderError cannot be fixed with “redirect_to and return”

转载 作者:行者123 更新时间:2023-12-03 08:20:17 26 4
gpt4 key购买 nike

今天,当我尝试为用户 Controller 使用一些辅助方法时,出现了此错误:

AbstractController::DoubleRenderError (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".)



我把以下助手放在 application_controller.rb中:
class ApplicationController < ActionController::Base

def current_user
User.find_by :id=>session[:user_id]
end

def log_in?
!!session[:user_id]
end

def log_in_first
if !log_in?
session[:error]="You have to log in first to continue your operation"
redirect_to("/login") and return
end
end

def correct_user?
if !(current_user.id.to_s==params[:id])
session[:error]="You have no right to do this operation."
redirect_to "/"
return
end
end
end

这是 user_controller.rb:
class UsersController < ApplicationController

def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.save
session[:user_id]=@user.id
redirect_to user_path(@user)
else
render 'new'
end
end

def show
log_in_first
@user = User.find_by id: params[:id]
correct_user?
if @user
render 'show'
else
redirect_to '/login'
end
end



private
def user_params
params.require(:user).permit(:name,:password,:email,:email_confirmation)
end
end

如您所见,我尝试在 returnand return中同时使用 log_in_firstcorrect_user?来解决此问题,但仍然无法正常工作。有人有什么想法吗?

最佳答案

问题出在show Action 中,log_in_first重定向,然后show Action 执行所需的操作,即重定向或渲染。这导致错误。

更好的解决方案是使用before_action进行身份验证和授权,并仅让用户 Controller 操作执行其任务。如下所示。

  class ApplicationController < ActionController::Base

def current_user
User.find_by :id=>session[:user_id]
end

def log_in?
!!session[:user_id]
end

def authenticate_user!
if !log_in?
session[:error]="You have to log in first to continue your operation"
redirect_to("/login")
end
end

def authorize_user!
unless current_user&.id.to_s==params[:id]
session[:error]="You have no right to do this operation."
redirect_to "/"
end
end
end

class UsersController < ApplicationController
before_action :authenticate_user!, only: [:show]
before_action :authorize_user!, only: [:show]

def new
@user = User.new
end

def create
@user = User.new(user_params)
if @user.save
session[:user_id]=@user.id
redirect_to user_path(@user)
else
render 'new'
end
end

def show
@user = User.find_by id: params[:id]
render 'show'
end

private
def user_params
params.require(:user).permit(:name,:password,:email,:email_confirmation)
end
end

关于ruby-on-rails - AbstractController::DoubleRenderError cannot be fixed with “redirect_to and return” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com