gpt4 book ai didi

ruby-on-rails - 为什么在 Rails 应用程序中呈现和重定向不会停止执行?

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:14 24 4
gpt4 key购买 nike

我有一个用例问题。在 Rails 4.1 中,如果你运行一个 Controller 方法并且在你的方法中的某个点有 redirect_to 或 render ,你仍然可以在那个点继续执行。如果您没有正确处理控制流,有时这会导致 AbstractController::DoubleRenderError。为什么在 Rails 中允许这样做?重定向而不停止执行似乎是一个有趣的用例,什么时候合适?

下面列出了完整的错误消息:

  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".

最佳答案

实际上错误消息说明了一切:

请注意,您只能调用渲染或重定向,并且每个操作最多一次。 另请注意,重定向和渲染都不会终止操作的执行所以如果你想在重定向后退出一个 Action ,你需要做一些像“redirect_to(...) and return”这样的事情

这是默认的 Rails 行为。

如果您尝试在单个操作中呈现多个 View ,您将收到 AbstractController::DoubleRenderError 错误。

要在渲染后停止执行,您必须显式使用 return 语句。

关于ruby-on-rails - 为什么在 Rails 应用程序中呈现和重定向不会停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com