Turbo Rails


What is Turbo Rails?

Turbo Rails is a collection of Javascript that operations behind the scenes and also an implementation of pattern for how Rails responds to requests on the backend

Importantly, our Rails app is now made up of turbo-frames, that look like this:

<turbo-frame id="new_message">
<form action="/messages" method="post">
...
</form>
</turbo-frame>

Here’s the explanation of what a Turbo Frame is, from the Turbo manual:

Turbo Frames allow predefined parts of a page to be updated on request. Any links and forms inside a frame are captured, and the frame contents automatically updated after receiving a response. Regardless of whether the server provides a full document, or just a fragment containing an updated version of the requested frame, only that particular frame will be extracted from the response to replace the existing content.

https://turbo.hotwired.dev/handbook/frames

• Turbo will intercept your links and forms. Yes, you! Yes, all of them. Unless you explicitly specify to disable it, all of your forms sent to the backend and links to new pages will operate differently from a traditional web app. They will be sent as TURBO_STREAM requests and Turbo will manage the page to swap out the relevant pieces of content.

In the Rails console that looks like this:

When you submit the form, the controller will process a TURBO_STREAM response.

Importantly, when there’s a failure, Rails now sends back an HTTP status code 422 (Unprocessable Entity).

A standard Rails respond block in a Turbo app might look something like this:

respond_to do |format|
format.turbo_stream
format.html
end

You’ll need to have partials that end with .turbo_stream.erb

The trick to using Turbo Stream:

In the partial, make sure that you are explicitly naming a replace whose id exactly matches an existing turbo-frame on the page.

Do I have to use Turbo Rails?

You do not, and for a Rails API-only application, it probably is a good idea to disable it.