Rendering a Partial Outside of a View or Controller in Rails 6

Primespot Engineering - June 04, 2020

Engineering

There are times when working within the Rails MVC architecture when you will want to render a partial from non-traditional areas of your application. Recently, I ran into this requirement while working with a rails library called cable_ready.

This library allows us to update the DOM from the server real-time over ActionCable. This is pretty cool, because it can replace a front-end library such as React in many situations with much less code.

You might see examples online where cable_ready is used to render a partial from within a controller. This works fine just the way you’d expect:

render "path/to/partial"

But what happens when you want to render this partial from outside of the normal scope?

For example, I wanted to use cable_ready to render the partial from within a Stimulus Reflex file. The render method won’t work here. At least not the same way.

Fortunately, the solution is very simple. Use this code:

ApplicationController.render "path/to/partial"

By simply scoping the render method to ApplicationController, everything should work fine. This will work within a Stimulus Reflex file and even from within a .js.erb file if you’re using that.

© 2020 Primespot Services. All rights reserved.