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

时间:2019-06-12 06:20:25

标签: ruby-on-rails modal-dialog

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

我打开函数after_sign_in_path_for(资源)并添加行 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

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

已重定向至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".):

2 个答案:

答案 0 :(得分:0)

默认装置将重定向到after_sign_in_path_for(资源),因此 after_sign_in_path_for(resource)必须是返回路径 在这种情况下,应该是

def after_sign_in_path_for(resource)
  root_path
end

def after_sign_in_path_for(resource)
  '\'
end

根本原因是此方法内的redirect_to,您有2次重定向到,所以我们遇到此错误

答案 1 :(得分:0)

我不确定语法,但是这里的概念是: redirect_to不会停止action方法的执行,因此,如果调用它,然后再调用render或另一个redirect_to,则将获得double render异常。有一个相当简单的修复方法,只需调用并返回即可。例如

redirect_to root_path and return

请参见Rails guide中的“避免双重呈现异常”。