Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4actioncontroller

Why does render and redirect not stop execution in a Rails app?


I have a use case question. In Rails 4.1 if you run a controller method and have redirect_to or render at some point in your method you are still allowed to continue execution at that point. Sometimes this results in a AbstractController::DoubleRenderError if you dont handle your control flow properly. Why is this allowed in Rails? It seems like a funny use case to redirect and not stop execution, when would this be appropriate?

The full error message is listed below:

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

Solution

  • Actually the error message is saying it all:

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

    This is the default Rails behaviour.

    If you try to render more than one view in a single action, you will get the AbstractController::DoubleRenderError error.

    To stop the execution after a render, you have to use return statement explicitly.