Last Updated: February 25, 2016
·
13.53K
· rshetty

Avoid Double Render errors in your Rails App

Often you end up in a situation where you try to render twice unknowingly in your Rails Application.

For Example :

def some_action
  redirect_to action: "somewhere"
  render action: "there" # raises DoubleRenderError
end

An Action may contain a single render or a single redirectto. Doing both as shown in above code raises Double Render Exception (Because 'redirectto' inturn makes another request to render the 'index' view.

Avoid both 'redirect_to' and render in a single action.

If you are using both based on some condition.

def some_action
  redirect_to (action: "somewhere") if something.nil?
  render action: "there"
end

The above code executes both statements and raises Double render exception when 'something is nil' So to avoid use use the above function as

def some_action
  redirect_to (action: "somewhere") and return if something.nil?
  render action: "there"
end

Using the return in the above code leads to return from that function and thus avoids 'Double Render Error' in your app.

That's it. Be careful the way you render your views in your action of the controller.

Happy Hacking!

Source : Rails Documentation in ActionController::Base class