为什么在 Rails 应用程序中呈现和重定向不会停止执行?
Why does render and redirect not stop execution in a Rails app?
我有一个用例问题。在 Rails 4.1 中,如果你 运行 一个控制器方法并且在你的方法中的某个点有 redirect_to 或渲染,你仍然可以在那个点继续执行。如果您没有正确处理控制流,有时这会导致 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".
实际上错误消息说明了一切:
请注意,您只能调用渲染或重定向,并且每个操作最多一次。 另请注意,重定向和渲染都不会终止操作的执行, 所以如果你想在重定向后退出一个动作,你需要做类似"redirect_to(...) and return".
的事情
这是默认的 Rails 行为。
如果您尝试在一个动作中渲染多个视图,您将收到 AbstractController::DoubleRenderError
错误。
要在渲染后停止执行,您必须明确使用 return
语句。
我有一个用例问题。在 Rails 4.1 中,如果你 运行 一个控制器方法并且在你的方法中的某个点有 redirect_to 或渲染,你仍然可以在那个点继续执行。如果您没有正确处理控制流,有时这会导致 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".
实际上错误消息说明了一切:
请注意,您只能调用渲染或重定向,并且每个操作最多一次。 另请注意,重定向和渲染都不会终止操作的执行, 所以如果你想在重定向后退出一个动作,你需要做类似"redirect_to(...) and return".
的事情这是默认的 Rails 行为。
如果您尝试在一个动作中渲染多个视图,您将收到 AbstractController::DoubleRenderError
错误。
要在渲染后停止执行,您必须明确使用 return
语句。