3

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".
nobody
  • 7,803
  • 11
  • 56
  • 91
  • 2
    As mentioned below, ask Rails Core Team, they're the only ones who can provide an authoritative answer on that. Until they speak up, we can't be sure. In general Ruby you can break execution with either `return` or `throw` (or `raise`, but that's for errors) and [this is used by Sinatra](http://www.sinatrarb.com/intro.html#Return%20Values), so it has proven to be a valid choice too. – D-side Sep 25 '15 at 21:52

1 Answers1

7

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.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • 1
    Right, sorry I guess I misspoke. I know that the error exists and everything, I was just curious as to exactly why this implementation exists. Like, wouldn't it make sense to just end execution at the render/redirect instead of throwing the exception? Why was Rails designed like this? – nobody Sep 25 '15 at 19:38
  • 3
    Yeah, that's a design question. I think you should ask that in the rails core team issue discussion ;) – K M Rakibul Islam Sep 25 '15 at 21:39