【问题标题】:Rails 5 - "Render and/or redirect were called multiple times in this action"Rails 5 - “在此操作中多次调用渲染和/或重定向”
【发布时间】:2017-04-08 03:26:05
【问题描述】:

更新到 Rails 5.0 后,我收到以下错误:

"AbstractController::DoubleRenderError in RegistrationsController#create

在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。另请注意,无论是重定向还是渲染都不会终止该操作的执行,因此如果您想在重定向后退出某个操作,则需要执行“reditect_to(...) and return”之类的操作。”

这是我的代码,在我更新之前可以使用:

def create
  # save record
  if params[:stuff].nil?
    respond_to do |format|
      format.js
    end
  else
    redirect_to root_path
  end
end

我尝试了很多不同的语法,例如:

redirect_to(root_path) and return

redirect_to(root_path)
return

return and redirect_to(root_path)

return redirect_to(root_path)

但一切都返回相同的错误。有人知道正确的语法吗?

【问题讨论】:

  • 您还有其他redirect_torender 在您的操作中吗?试试看:return redirect_to(root_path).
  • @Gerry 我添加了完整的操作。该代码也不起作用。
  • 由于没有其他 redirect_torender 存在,我还建议使用 byebug 来定位您的代码调用第二次渲染的位置。

标签: ruby-on-rails ruby redirect controller ruby-on-rails-5


【解决方案1】:

您可能在显示# save-record 的位置进行了渲染或重定向。

试试这个:

  • 如果你还没有安装 gem byebug 到你的 Gemfile 中,运行 bundle 来安装它,然后重启 Rails
  • byebug 添加到create 方法的开头
  • 从浏览器或命令行调用create,并使用ns 单步执行以单步执行其他功能。你可能会注意到 render 或 redirect 被调用了两次

【讨论】:

  • 我没有在我的操作中使用renderredirect_to 的任何其他实例。
【解决方案2】:

您可以使用performed? 来测试或调试双重渲染/重定向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多