Fixing "AbstractController::DoubleRenderError" in Rails.

For some weird reasons, Ruby on Rails [sometimes] doesn't seem to like "rendering" a view or redirection being done more than once in a code block. One would expect that when they render a view or redirect to a URL at a specific point in their code, the rest of the execution would be skipped but that doesn't look to be the case for these two helper methods, "#render()" and "#redirect_to()" in ROR views.

When you do something like this:

Code that might potentially throw an error [image]

You might get the following error when you run your RSpec tests:


  1) UsersController create redirects you if your password and confirmation don't match
     Failure/Error: redirect_to({controller:  'users', action: 'welcome'})
       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".
# ./app/controllers/users_controller.rb:11:in `create'
# ./spec/controllers/users_controller_spec.rb:27:in `block (3 levels) in '

So what do we do to fix this?

One of the ways I got around fixing this error was making sure I had a mention of "#redirect()" only once in an action. To do this I had a redirect URL set as a variable and then redirect to that only at the end after the desired execution path has been determined.

Here is one way you could implement the fix for that problem...

Fix 1 [image]

A shorter and preferred version of the fix is as shown below...

Fix 2 [image]

Super note: This error is kind of intermittent and this fix is like the fail-safe that could catch possible edge cases to avoid it altogether