Take care when using `render` in Rails

The more I experiment with other technologies, the more I realize what a joy it is to work with Rails and Ruby every single day.

I take for granted the baked-in convention-over-configuration ethos, which allows developers to maximize their efforts with genuine building and creativity.

Take for example the following:

Implicit rendering

When spinning up a new action in ActionController, you do not need to specify what template to render. As long as the namespaces match and are found in app/views, your application will do the work for you. If you stay RESTful on a CRUD app you may rarely if ever find yourself manually rendering templates.

See? It knows to spit out the associated view. This is the kind of joy you experience from day one with the framework.

Explicit rendering

There will be times when we stray as we continue building larger applications. That’s okay though! Rails is convention over configuration, not the banishment of configuration altogether. In that case we can send the template explicitly down….

… and Rails knows what we’re about.

Extra curricular activity

That doesn’t mean we can’t overlook something big. It’s important to note the easily-missed case where we can be executing unexpected code. Take the following example:

It may be obvious from such a small controller action, but this can easily be missed as controllers get more fat. All code after a redirect or renderis still executed. That means in this case we see this page:

But if we refresh we notice that our title indeed was updated behind the scenes.

While building out controllers and especially as they get larger, be sure to take care to consider code that may be executed after.

Handling DoubleRenderError

Worth remembering is that render or redirect code is executed more than once. See below:

You’ve probably encountered this error a fair few times yourself. Most likely as controllers are growing. If you find yourself unable to remove the render or redirect (which I recommend trying first) you can resolve this by calling and return after the render is hit.

This also precludes all later code from executing, which is a handy tool in the event that you not only want to prevent a DoubleRenderError, but stop later code from executing.

When we visit '/books/blocks_double_render_error' we can clearly see that the code has not executed on the title attribute.

Conclusion

If you want to have a play with this yourself, I fired up a repo with the example code that you can access.