Real-Time Updates in Rails: Harnessing Turbo Frame and Turbo Stream

In modern web development, delivering real-time updates in Rails applications has become essential for creating dynamic and engaging user experiences. One effective way to achieve this is by utilizing Turbo Frame and Turbo Stream. If you're looking to implement these features efficiently, choosing Ruby on Rails development company can help guide you through the process, from installation to implementation, covering all the essential concepts in Rails 7.

What is Turbo?

Turbo is a lightweight framework designed for real-time updates in Rails applications. It leverages the power of WebSockets to push updates to clients without requiring page reloads. The two key components that make real-time data streaming possible in Rails 7 are:

  • Turbo Frame: This component wraps sections of your HTML that you want to update in real-time.
  • Turbo Stream: This component broadcasts changes to Turbo Frames, ensuring all clients receive updates instantly.

Benefits of Using Turbo Frame and Turbo Stream

  1. Improved Performance: By updating only parts of the page, Turbo reduces data transfer and processing, resulting in quicker responses and lower server load.
  2. Enhanced User Experience: Users enjoy seamless interactions with fewer full-page reloads, making your application feel more responsive and engaging.
  3. Simplified Code: Turbo simplifies front-end code, reducing the need for complex JavaScript and AJAX calls.

Key Turbo Stream Actions in Rails

Here’s a detailed look at the key actions available with Turbo Stream in Rails 7:

  • Append: Adds content at the end of a target element.
    Usage: Adding new items to a list.
    Example: Adding a new comment to a comment section.
  • Prepend: Inserts content at the beginning of a target element.
    Usage: Placing new items at the top of a list.
    Example: Adding a new message to a chat window.
  • Replace: Replaces the content of the target element with new content.
    Usage: Updating a section of a page.
    Example: Updating user profile details.
  • Update: Updates the content of the target element's inner HTML.
    Usage: Refreshing parts of a page.
    Example: Updating a score in a live display.
  • Remove: Deletes the target element from the DOM.
    Usage: Removing items that are no longer needed.
    Example: Removing a notification.

Getting Started with Turbo in Rails 7

Installation

To get started with real-time updates in Rails, ensure your Rails application is running on Rails 7 or later, as Turbo is integrated into Rails by default. If you're using an older version, you can manually install the Turbo gem. If you're looking to leverage the full potential of Turbo in your projects, it's essential to hire Ruby on Rails developers who are experienced with the latest Rails updates and Turbo's powerful features.

To begin, add the turbo-rails gem to your Gemfile:

gem 'turbo-rails'

After updating your Gemfile, run bundle install to install the gem.

Here is the example of Real-time Updates with Turbo Streams

In this example, we'll implement a dynamic blacklisting feature for customers. Users can blacklist or undo blacklist a customer without the need for page refresh, thanks to Turbo Streams. Let's walk through how to set up and implement this feature step by step.

  1. Update the Customer View Page

In the view page of customer details , add a section to blacklist or undo blacklist the customer with the help of turbo frame tag.

<div class="mt-4 flex justify-center">
  <%= turbo_frame_tag :blacklist_button do %>
    <%= render partial: "admin/shared/blacklist" %>
  <% end %>
</div>
  1. Define the Route

Define the route for the blacklist action.
config/routes.rb

namespace :admin do
  resources :customers, except: [:destroy] do
    member do
      post :blacklist
    end
  end
end
  1. Create Partial for Blacklist Button

Create a partial to handle the display of the blacklist button.
app/views/admin/shared/_blacklist.html.erb

<div class="mt-4">
  <% if @customer.blacklist? %>
    <%= button_to "Undo Blacklist", 
        blacklist_admin_customer_path(@customer), 
        method: :post, class: 'btn btn-solid' %>
  <% else %>
    <%= button_to "Blacklist", blacklist_admin_customer_path(@customer), 
        method: :post, class: 'text-primary px-5 py-2 rounded border' %>
  <% end %>
</div>
  1. Controller Action for Blacklist

Handle the blacklist action in the controller.
app/controllers/admin/customers_controller.rb

def blacklist
  respond_to do |format|
    if @customer.update(blacklist: !@customer.blacklist)
                        format.turbo_stream
    else
      format.json { render json: @customer.errors, status: 
                    :unprocessable_entity }
    end
  end
end
  1. Create the Turbo Stream View

Create a Turbo Stream view to handle the update of the blacklist button.
app/views/admin/customers/blacklist.turbo_stream.erb

Output:

Lazy Loading with Turbo in Rails:

Lazy loading is a design pattern that defers the loading of resources (such as images, components, or data) until they are actually needed. In web development, this approach is commonly used to optimize performance by loading non-critical content only when it becomes visible (e.g., when the user scrolls to it).

This technique is especially useful for pages with a lot of content or media, as it reduces the initial load time and improves the user experience by prioritizing essential elements.

Rails makes lazy-loading easy with its turbo_frame_tag element.

<%= turbo_frame_tag :frame_name, src: src_path, loading: :lazy do %>
  Temporary content while we're loading...
<% end %>

What's going on here?

It's really simple — this Turbo Frame will load the contents of a different Turbo Frame, and overwrite its current content with the new content.

The new content comes from a Turbo Frame with a matching :frame_name, located at the src_path.

By setting loading: :lazy, we can make our Turbo Frame do this loading lazily. While we're waiting, the contents inside the current turbo_frame_tag will be displayed.

Pros of Lazy Loading:

  • Faster Page Load Times – Only essential content loads first, improving performance.
  • Reduced Bandwidth Usage – Saves data by loading resources only when needed.
  • Better User Experience – Users interact with the page faster without delays.
  • Improved Mobile Performance – Minimizes resource consumption on slower networks.
  • Lower Server Load – Reduces unnecessary requests, saving hosting resources.

Here is the example of Lazy Loading in Rails:

In this example we'll implement lazy loading for list all posts.

  1. To create a basic lazy loader, adjust your posts/index.html.erb to include a turbo_frame_tag 
<div class="w-full">
  <p class="text-xl font-bold">Lazy loading with Hotwire and Turbo 
      Frames</p>
  <%= turbo_frame_tag :posts_lazy, src: posts_index_lazy_path, loading: 
      :lazy do %>
  <% end %>
</div>

This turbo_frame_tag is going to lazily call the posts_index_lazy_path route, and try to find another turbo_frame_tag called :posts_lazy.

  1. In your PostsController, you need to add a new controller action for our view
def index_lazy
  @posts = Post.all
end
  1. Then we need to map our new Posts#index_lazy controller action to a route file.
Rails.application.routes.draw do
  get 'posts/index_lazy', to: 'posts#index_lazy'
  resources :posts
end
  1. And finally, we need to create a view for our new Posts#index_lazy controller action.
<%= turbo_frame_tag :posts_lazy do %>
  Count: <%= @posts.count %>
  <%= render @posts %>
<% end %>

Output:

Summary:

This setup empowers users to perform blacklisting or undoing of blacklisting actions for a customer seamlessly, without necessitating a page refresh. Upon triggering the blacklist or undo blacklist button, an asynchronous request is dispatched to the server, which updates the customer's blacklist status and subsequently renders an appropriate Turbo Stream response to reflect the button's updated state.

By integrating Turbo Frame and Turbo Stream into your Rails 7 application, you can significantly enhance user experience and application performance through real-time updates. Start implementing these features today to keep your users engaged and improve the responsiveness of your application!

Like it!
If you found this guide helpful, share it with fellow developers and leave a comment below with your experiences using
Turbo in your projects!


FAQs

  1. What is Turbo in Rails?
    Turbo is a lightweight framework integrated into Rails 7 that enables real-time updates by pushing changes to clients without page reloads. It leverages components like Turbo Frame and Turbo Stream for enhanced performance.

  2. How does Turbo Frame work?
    Turbo Frame allows developers to wrap sections of HTML that need real-time updates, ensuring only part of the page reloads, improving speed and efficiency.

  3. What are the key actions available in Turbo Stream?
    Turbo Stream provides actions like append, prepend, replace, update, and remove, each designed to manipulate elements dynamically in real-time.

  4. How do Turbo Frame and Turbo Stream enhance performance?
    By updating only specific parts of the page and reducing the need for full reloads, they decrease server load, resulting in faster responses and improved user experiences.

  5. What is the process for implementing Turbo in Rails 7?
    To implement, ensure your app is running on Rails 7, add the turbo-rails gem, and follow steps like creating Turbo Stream views and defining routes to update elements in real-time.