Skip to content

Blogging On Rails

Everything on Rails!

HOTWire Tutorial: Listening for changes over ActionCable

Many of the changes in Turbo 8 are incredibly promising for improving the perception of speed and interactivity on our web apps.

A lot of my Stimulus Tutorials need an update since they were first written, so follow along to update existing tutorials and rethink them with the newest tools available. Today we obsolete the tutorials Grabbing ActionCable with Stimulus.js and Subscribing to many channels in ActionCable.

Moving on from the Stimulus controllers

The initial tutorials required creating a Stimulus controller and calling the ActionCable code to setup the web socket connection. Now, Turbo automatically sets up those connections if the HTML includes the turbo_stream_from directive. In the Todo example, this means we could add the following to todos\_todo.html:

<%= turbo_stream_from todo %>

The generated HTML will look something like:

<turbo-cable-stream-source channel="Turbo::StreamsChannel" 

Turbo has its own channel that will subscribe to all the names, and the channel name gets encrypted to protect from someone trying to guess the value.

No extra Channels

The previous examples also required setting up a ActionCable channel to stream events. Since we use the Turbo channel, this is no longer required. Instead, the model that needs to stream updates adds a helper method, and on creation, updates, and deletion, it gets events broadcasted over the Turbo channel. The change in Turbo 8 is that instead of needing to send new HTML over the web socket, the page refreshes and morphs the new elements to make it appear like everything changed.

The Todo item needs broadcasts_refreshes and all these updates are sent automatically to the front end for those Todos that are listened to.

Listening for new Todos

When creating a new Todo, there isn’t an existing channel listening for that Todo. Turbo handles this by broadcasting creations to a model specific channel, "todos" in this case. In todos\index.html.erb: adding the stream from directive will load in the Todos to the list:

<%= turbo_stream_from Todo.model_name.plural %>

Touch to broadcast changes

When dragging and dropping the Todos, the upsert operation doesn’t automatically toggle a broadcast to make the front end refresh. By calling the touch method on the todo that was dragged, the front end is notified of the change, and the page refreshes with the updates.



The changes to Turbo over the past few years have allowed for better interactivity and better developer speed. These improvements are exceptional.

You can see the code on Github.

Leave a Reply

Your email address will not be published. Required fields are marked *