【问题标题】:Can't get rid of AbstractController::DoubleRenderError无法摆脱 AbstractController::DoubleRenderError
【发布时间】:2012-05-04 21:24:48
【问题描述】:

我在模型的更新方法中遇到双重渲染错误。

这是控制器的代码

class Admin::CmsHappeningNowFeatureController < ApplicationController

    def index
        # Various model data retrieval...

        render 'admin/cms/hn_features/index', layout: 'admin_cms'
    end

    # Works fine
    def edit
        @feature = CmsHappeningNowFeature.find_by_id(params[:id])
        render 'admin/cms/hn_features/feature', layout: 'admin_cms'
    end

    # Throws a AbstractController::DoubleRenderError upon submission
    def update
        @feature = CmsHappeningNowFeature.find_by_id(params[:id])
        @feature.attributes = params[:cms_happening_now_feature]
        if @feature.save
            redirect_to(:action => index, :notice => "Successfully updated feature.") and return
        end 
        render 'admin/cms/hn_features/feature', layout: 'admin_cms'
    end

    # ... rest of the class
end

当重定向到另一个控制器时,问题就消失了。似乎重定向到同一个控制器会使 rails 执行该方法而无需实际发送重定向。通过查看日志,提交更新表单时,update 被调用,然后index 被调用,render from index 被执行,然后重定向失败。 p>

我错过了什么?解决方法是什么?

【问题讨论】:

    标签: ruby-on-rails-3 model controller


    【解决方案1】:

    好吧,真正的原因是在

    redirect_to(:action => index, :notice => "Successfully updated feature.") and return
    #                      ^^^^^ This calls the index method
    

    您调用index 方法,然后该方法将首先呈现。然后redirect_to 调用将返回该函数的结果(这将是index 中的rendercall 返回的任何结果)。并第二次渲染

    你真正想写的是:

    redirect_to(:action => :index, :notice => "Successfully updated feature.") and return
    

    您将:action 设置为符号的位置,即表示操作但不直接调用它的索引。

    【讨论】:

    • 哈!谢谢!我没有注意到:action =&gt; index 实际上是在调用index 并将结果返回给:action
    【解决方案2】:

    你有

    if @feature.save
       redirect_to(:action => index, :notice => "Successfully updated feature.") and return
    end 
    

    重定向到索引,然后再次从索引重定向,引发错误

    试试这个,让我知道它是否有效:

    if @feature.save
       index
       flash[:notice] = "Successfully updated feature." 
       return
    end 
    

    【讨论】:

    • 这行得通,但是,url 不会更新,如果用户点击刷新,表单会被重新提交,这是一个很大的缺点......这是使用重定向的全部优势。我设法解决这个问题的唯一方法是指定一个路径,例如redirect_to admin_cms_hn_feature_index_path, :notice =&gt; "Successfully updated feature." and return
    • 我不知道为什么redirect_to 命令会在重定向到它之前实际执行操作index。这令人困惑,而不是您对命令的期望。
    【解决方案3】:

    我也遇到了这个问题,但是它不涉及任何重定向或控制器中的多个渲染。我们有一个直接触发电子邮件的操作,没有后端队列可以放置它。这使用 ActionMailer gem,我相信它会在 .haml 或其他模板上进行渲染以生成电子邮件的 html。然后我们在发送电子邮件后使用 在结束时渲染更新调用

    这会导致此错误吗? Rails 认为 ActionMailer 的电子邮件模板渲染是常规渲染?这只是一个猜测,不知道还有什么可能......我也无法 100% 重现它,但看起来不像是并发的东西,因为在日志中我只看到一个对控制器的调用。

    欢迎任何想法,谢谢。

    【讨论】:

    • 仅供参考,我发现了这个原因。如果 rabl 以某种方式设置了一个子节点并且它期望一个项目但得到多个,这可能会发生。所以它有点像一个包含 rabl 的孩子会意外地渲染两次,这会发生。我对此感到惊讶,以为 json 会有双重/额外数据。
    猜你喜欢
    • 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
    相关资源
    最近更新 更多