【问题标题】:<AbstractController::DoubleRenderError in controller<AbstractController::DoubleRenderError 在控制器
【发布时间】:2014-09-14 12:01:48
【问题描述】:

我收到此错误,我尝试添加一个 redirect_to() 并返回我的 access_doc_or_redirect() 方法,但没有运气。有什么建议吗?

 def access_doc_or_redirect(doc_id, msg)
   doc = Document.find(params[:id])
   if doc.user_access?(current_user)
     @document = doc
   else
     flash[:alert] = msg
     redirect_to root_url and return
   end
 end

 def get
   access_doc_or_redirect(params[:id], "Sorry, no document view access.")
   redirect_to @document.file.url
 end

错误

access_doc_or_redirect(params[:id], "Sorry, no document view access" AbstractController::DoubleRenderError: 在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且在每个动作最多一次。还要注意,重定向和渲染都不会终止动作的执行,所以如果你想在重定向后退出一个动作,你需要做一些类似“redirect_to(...) and return”的事情。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    AbstractController::DoubleRenderError:在此操作中多次调用渲染和/或重定向。

    错误是自我描述的,您在操作中多次调用渲染或重定向。让我们看看你的方法:

    def access_doc_or_redirect(doc_id, msg)
      doc = Document.find(params[:id])
      if doc.user_access?(current_user)
        @document = doc  
        #this block will run fine and return @document to get method
      else
        flash[:alert] = msg
        redirect_to root_url and return
        #this block is giving you trouble because you are redirecting to root url and then control goes back to your get method where you are using redirect again and hence double render error
      end
    end
    

    修复:

    如果您将其用作过滤器,那么您可以执行以下操作来修复错误:

    def get
      #i think this is your main method so you should use redirect or render inside this method only
      #instance variables set inside access_doc_or_redirect will automatically be available inside this method
      if @document 
        redirect_to @document.file.url
      else
        flash[:alert] = "Sorry, no document view access."
        redirect_to root_url
      end
    end
    
    def access_doc_or_redirect
      @doc = Document.find(params[:id])
      if @doc.user_access?(current_user)
        @document = doc
      end
    end
    

    【讨论】:

    • 谢谢,但问题是我试图保持代码干燥,并将 access_doc_or_redirect 保持为 before_filter。为什么“并返回”不起作用?
    • @user2012677 正如我在回答中使用 return 解释的那样,它将从 access_doc_or_redirect 方法中返回,并且控制将转到 get 方法,并且您再次在那里使用重定向,因此您的错误
    • 我该如何重定向和“END”呢?
    • @user2012677 更新了我的答案,我认为这也是你能做的最好的方法,因为 get 方法是你的主要方法,而另一个只是一个过滤器,所以在里面重定向是有意义的获取方法
    猜你喜欢
    • 2015-11-27
    • 2014-07-02
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    相关资源
    最近更新 更多