Cesare Ferrari

July 19, 2022

What is Turbo Drive

Turbo Drive is a technology implemented in Ruby on Rails that speeds page loads. It does so by intercepting link click and form submission events and converting them to Ajax requests to the server.

It then takes the HTML responses returned by the server as a result of these requests and updates the <body> of the page in the browser, so there won’t be a full page reload.

The result is a faster refresh of the page, similar to what happens with a single page application.

While single page application typically receive JSON responses, Rails will still receive HTML responses, that are then managed by Turbo Drive.

Turbo Drive is set up automatically in Rails 7, so there is no need to activate it. It’s implemented through the turbo-rails gem, installed by default in a new Rails 7 app.


Unprocessable entity

One thing to note while working with Turbo Drive is that unsuccessful form submissions must return a 422 status code for Turbo Drive to display the form errors correctly.

For this reason, in our controller’s create and update actions we need to return a 422 status code when something goes wrong and we need to re-render the new or edit page with errors.

In Rails, a 422 error is aliased as :unprocessable_entity, which we must pass to the render method, like the example below:

  def create
    @document = Document.new(document_params)

    if @document.save
      respond_to do |format|
        format.html { redirect_to admin_documents_url, notice: "Document created successfully." }
      end
    else
      respond_to do |format|
        format.html do
          flash.now[:alert] = "Please fix errors below."
          render :new, status: :unprocessable_entity
        end
      end
    end
  end

More information on Turbo Drive can be found here: https://turbo.hotwired.dev