如何修复“在此操作中多次调用渲染和/或重定向”

Ole*_*sov 1 ruby-on-rails modal-dialog

我有一个用于记录的模式窗口。当我按下提交时,我正在记录,但手动重新加载页面后我可以看到结果

我打开函数 after_sign_in_path_for(resource) 并添加行redirect_to root_path 并返回 true

class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception
    before_action :configure_devise_permitted_parameters, if: 
  :devise_controller?
    before_action :set_referral_cookie
    before_action :blog_redirect
    force_ssl unless: :ssl_configured?
  #   skip_before_action :verify_authenticity_token
    before_action :redirect_logins

    def redirect_logins 
      if request.fullpath.match('users/sign_in') && request.get?
        redirect_to '/?sign_in=true'
      end
    end

    def after_sign_in_path_for(resource)
      redirect_to root_path
      '/'
    end

    def ssl_configured?
      puts request.original_url
      Rails.env.development? || !!request.original_url.match('/blog')
    end

    def blog
      redirect_to "https://www.xxx.xx/blog#{request.fullpath.gsub('/blog','')}", :status => :moved_permanently
     end
Run Code Online (Sandbox Code Playgroud)

在控制台中,我收到一条消息

重定向到http://localhost:3090/ 在 755 毫秒内完成 500 内部服务器错误(ActiveRecord:491.9 毫秒)

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".):
Run Code Online (Sandbox Code Playgroud)

小智 5

我不确定语法,但这里的概念是: redirect_to不会停止操作方法的执行,因此如果您调用它并稍后调用渲染或其他方法,redirect_to您将得到双重渲染异常。有一个相当简单的修复方法,只需调用并返回即可。例如

redirect_to root_path and return
Run Code Online (Sandbox Code Playgroud)

请参阅Rails 指南中的“避免双重渲染异常” 。