Ruby on rails 3 Can';t摆脱AbstractController::DoubleRenderError
我得到了一个双重渲染错误,我无法在模型的更新方法中消除它 这是控制器的代码Ruby on rails 3 Can';t摆脱AbstractController::DoubleRenderError,ruby-on-rails-3,model,controller,Ruby On Rails 3,Model,Controller,我得到了一个双重渲染错误,我无法在模型的更新方法中消除它 这是控制器的代码 class Admin::CmsHappeningNowFeatureController < ApplicationController def index # Various model data retrieval... render 'admin/cms/hn_features/index', layout: 'admin_cms' end #
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
类管理员::CMShapOpenNowFeatureControllerindex,:notice=>“已成功更新的功能”)并返回
结束
呈现“管理/cms/hn_功能/功能”,布局:“管理/cms”
结束
# ... 班上其他同学
结束
重定向到其他控制器时,问题消失。似乎重定向到同一个控制器会使rails执行该方法,而不实际发送重定向。通过查看日志,在提交更新表单时,update
被调用,然后index
被调用,执行render
from index,然后发出重定向并失败
我错过了什么?解决方法是什么?您有
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
好吧,真正的原因是
redirect_to(:action => index, :notice => "Successfully updated feature.") and return
# ^^^^^ This calls the index method
调用index
方法,该方法将首先渲染。redirect_to
调用将返回该函数的结果(无论render
调用在index
中返回什么)。并进行第二次渲染
你真正想写的是:
redirect_to(:action => :index, :notice => "Successfully updated feature.") and return
您将
:action
设置为一个符号,即表示操作但不直接调用它的索引。我也遇到了这个问题,但它不涉及任何重定向到控制器或控制器中的多个渲染。我们有一个直接触发电子邮件的操作,没有后端队列来放置它。这将使用ActionMailerGem,我相信它会在.haml或其他模板上进行渲染,以生成电子邮件的html。然后我们在发送电子邮件后使用了
在结束时渲染更新调用
这会导致这个错误吗?Rails认为ActionMailer对电子邮件模板的呈现是常规呈现吗?这只是一个猜测,不确定它还能是什么……而且我不能100%地重现它,但看起来不像并发性,因为在日志中,我只看到一个对控制器的调用
欢迎任何想法,谢谢。这很有效,但是url不会更新,如果用户点击“刷新”,表单会重新提交,这是一个很大的缺点。。。这就是使用重定向的全部优点。我设法解决这个问题的唯一方法是指定一个路径,例如
redirect\u to admin\u cms\u hn\u feature\u index\u path,:notice=>“Successfully updated feature.”并返回
我不知道为什么redirect\u to命令会在重定向到它之前实际执行操作index
。这是令人困惑的,不是你从命令中所期望的。哈!谢谢我没有发现:action=>index
实际上正在调用index
并将结果返回给:action
供参考,我发现了原因。如果rabl以某种方式与子节点一起设置,并且子节点期望一个项,但得到多个项,则会出现这种情况。所以它有点像一个包含rabl的孩子,会在未预料的情况下被渲染两次。我对此感到惊讶,以为json会有双重/额外的数据。