In Part 4 we modeled plans, topics and study sessions. It works, but every click is a full page load. Add a topic, wait for the reload, scroll back to where you were.
Rails 8 ships with Hotwire, a set of tools that make pages update in place while you keep writing Ruby and ERB. In this post we use two of them, Turbo Frames and Turbo Streams, to add and edit topics and run study sessions without leaving the page.
What you'll learn
- What Turbo Drive already does for you (for free)
- Turbo Frames: swapping one piece of a page
- Turbo Streams: changing several pieces of the page at once from the server
-
respond_towithformat.turbo_stream -
dom_idandturbo_frame_tag - Showing flash messages with Turbo
The idea in one minute
Hotwire's bet: send HTML, not JSON. The server renders the HTML (it already knows how), and the browser swaps it into the page. No front-end framework, no API layer.
| Tool | What it does | Think of it as |
|---|---|---|
| Turbo Drive | Turns link clicks and form submits into background requests and swaps the <body>
|
A page change without the white flash |
| Turbo Frames | Updates one region of the page | A window you can change |
| Turbo Streams | Sends small instructions: "append this here, remove that there" | A remote control for the page |
Step 1: Turbo Drive: already running
Open app/javascript/application.js. A new Rails 8 app starts with:
import "@hotwired/turbo-rails"
and config/importmap.rb pins it. That's all. Since Part 1, every link and form in Study Flow has been handled by Turbo Drive. You can see it as the thin progress bar at the top of the page.
This is also why we've been writing status: :unprocessable_content when a form fails and status: :see_other after a DELETE redirect. Turbo Drive reads those status codes to decide what to show.
Step 2: Turbo Frames: edit a topic in place
A frame is a rectangle of the page, marked with an id:
<%= turbo_frame_tag "new_topic" do %>
<%= link_to "Add a Topic", new_topic_path(study_plan_id: @study_plan.id) %>
<% end %>
This renders <turbo-frame id="new_topic">…</turbo-frame>. The rule that makes frames work is:
A link or form inside a frame loads its response, finds the frame with the same id in that response, and swaps only that part.
So when you click "Add a Topic", Turbo requests /topics/new?study_plan_id=1 and looks for <turbo-frame id="new_topic"> in the answer. The topic form page contains one:
<%# app/views/topics/new.html.erb %>
<%= turbo_frame_tag "new_topic" do %>
<% if @topic.errors.any? %>
<p class="text-red-500"><%= @topic.errors.full_messages.to_sentence %></p>
<% end %>
<%= form_with model: @topic do |form| %>
<%= form.hidden_field :study_plan_id, value: @topic.study_plan_id %>
<%= form.text_field :name, required: true, autofocus: true, placeholder: "name" %>
<%= form.text_field :description, placeholder: "description" %>
<%= form.number_field :estimated_hours, required: true, placeholder: "estimated hours" %>
<%= form.submit "Add Topic" %>
<% end %>
<% end %>
<%= link_to "Back to Study Plan", study_plan_path(@topic.study_plan) %>
The link "Add a Topic" is replaced by the form, in the same spot. Nothing else on the page moves.
Two details matter:
-
Errors go inside the frame. If the form fails (422), Turbo extracts the
new_topicframe from the response and drops everything outside it. An error message placed outside the frame would never be seen. - Visit
/topics/new?study_plan_id=1directly and the page still works as a normal full page. Frames are progressive: the same URL serves both.
Editing a topic in place
Give every topic its own frame. dom_id(topic) generates a unique id like topic_7:
<%# app/views/study_plans/show.html.erb %>
<h2 class="font-bold text-2xl mt-6">Topics</h2>
<div id="topics">
<% @study_plan.topics.each do |topic| %>
<%= turbo_frame_tag dom_id(topic) do %>
<div class="mb-2">
<%= render "topics/topic", topic: topic %>
</div>
<% end %>
<% end %>
</div>
<%= turbo_frame_tag "new_topic" do %>
<%= link_to "Add a Topic", new_topic_path(study_plan_id: @study_plan.id) %>
<% end %>
And the edit page contains a frame with the same id. turbo_frame_tag @topic builds it from the record, so the id is topic_7 again:
<%# app/views/topics/edit.html.erb %>
<%= turbo_frame_tag @topic do %>
<% if @topic.errors.any? %>
<p class="text-red-500"><%= @topic.errors.full_messages.to_sentence %></p>
<% end %>
<%= form_with model: @topic do |form| %>
<%= form.hidden_field :study_plan_id, value: @topic.study_plan_id %>
<%= form.text_field :name, required: true, autofocus: true %>
<%= form.text_field :description %>
<%= form.number_field :estimated_hours, required: true %>
<%= form.submit "Update Topic" %>
<% end %>
<% end %>
Click "Edit" next to a topic, the topic turns into a form. Same-id matching does all the work.
Step 3: Turbo Streams: the server tells the page what to do
Frames swap the frame you clicked in. But after adding a topic we need to do two things: append the new topic to the list, and put the "Add a Topic" link back. For that we use Turbo Streams, which are instructions with an action and a target:
<turbo-stream action="append" target="topics">
<template>…new HTML…</template>
</turbo-stream>
| Action | What it does |
|---|---|
append / prepend
|
Add inside the target, at the end or start |
before / after
|
Add next to the target |
update |
Replace the target's contents |
replace |
Replace the whole target |
remove |
Delete the target |
In ERB, the turbo_stream helper writes these for you. Put one template per action, named after the format:
<%# app/views/topics/create.turbo_stream.erb %>
<%= turbo_stream.append "topics" do %>
<%= turbo_frame_tag dom_id(@topic) do %>
<div class="mb-2">
<%= render "topics/topic", topic: @topic %>
</div>
<% end %>
<% end %>
<%= turbo_stream.update "new_topic" do %>
<%= link_to "Add a Topic", new_topic_path(study_plan_id: @topic.study_plan_id) %>
<% end %>
<%# app/views/topics/update.turbo_stream.erb %>
<%= turbo_stream.update dom_id(@topic) do %>
<div class="mb-2">
<%= render "topics/topic", topic: @topic %>
</div>
<% end %>
<%# app/views/topics/destroy.turbo_stream.erb %>
<%= turbo_stream.remove dom_id(@topic) %>
Because the new topic is appended into <div id="topics">, the list stays valid HTML.
Choosing the format in the controller
Back in TopicsController, we answer in either format:
def create
@topic = @study_plan.topics.new(topic_params)
if @topic.save
respond_to do |format|
format.turbo_stream { flash.now[:notice] = "Topic created successfully." }
format.html { redirect_to study_plan_path(@study_plan), notice: "Topic created successfully." }
end
else
render :new, status: :unprocessable_content
end
end
def destroy
@topic.destroy
respond_to do |format|
format.turbo_stream { flash.now[:notice] = "Topic deleted successfully." }
format.html { redirect_to study_plan_path(@topic.study_plan), notice: "Topic deleted successfully.", status: :see_other }
end
end
respond_to picks the branch from what the browser says it accepts. Turbo adds text/vnd.turbo-stream.html to form submissions, so Turbo gets the stream; anything else (JavaScript disabled, curl, a bookmarked link) gets the plain HTML redirect. Your app keeps working without Turbo, and that's a feature.
In the turbo_stream branch we don't call render. Rails then renders the template matching the action name (create.turbo_stream.erb) automatically.
Step 4: Flash messages with streams
flash.now[:notice] sets a message for this response only, which is right for a stream. But nothing shows it yet. Let's make a single place for flash messages.
<%# app/views/shared/_flash.html.erb %>
<% if flash[:alert] %>
<p class="py-2 px-3 bg-red-50 mb-5 text-red-500 font-medium rounded-lg inline-block"><%= flash[:alert] %></p>
<% end %>
<% if flash[:notice] %>
<p class="py-2 px-3 bg-green-50 mb-5 text-green-500 font-medium rounded-lg inline-block"><%= flash[:notice] %></p>
<% end %>
Render it once in the layout, inside <main>, above yield, in an element with an id:
<%# app/views/layouts/application.html.erb %>
<div id="flash"><%= render "shared/flash" %></div>
<%= yield %>
(Delete the render "shared/alert" lines from individual views.) Then end each stream template with one line:
<%= turbo_stream.update "flash", partial: "shared/flash" %>
Now regular page loads show the flash from the layout, and stream responses refresh the same #flash element. A good rule of thumb:
-
redirect_to … notice:→ useflash(the next request shows it) -
render …or a stream → useflash.now(only this response shows it)
Step 5: Study sessions with frames and streams
Sessions use the same recipe, with one new twist: one stream template can touch several places.
The "Start a study session" link lives in its own frame inside the topic partial, and the sessions go into a list with a matching id:
<%# app/views/topics/_topic.html.erb (the sessions part) %>
<%= turbo_frame_tag "#{topic.id}_new_study_session" do %>
<% if topic.study_sessions.active.empty? %>
<%= link_to "Start a study session", new_study_session_path(topic_id: topic.id) %>
<% end %>
<% end %>
<div>Study Sessions:
<div id="<%= topic.id %>_sessions">
<% topic.study_sessions.each do |study_session| %>
<%= turbo_frame_tag study_session do %>
<div class="mb-2"><%= render "study_sessions/session", session: study_session %></div>
<% end %>
<% end %>
</div>
</div>
Starting a session adds it to the list and clears the "Start" link, so only one session can be running:
<%# app/views/study_sessions/create.turbo_stream.erb %>
<%= turbo_stream.append "#{@study_session.topic_id}_sessions" do %>
<%= turbo_frame_tag dom_id(@study_session) do %>
<div class="mb-2"><%= render "study_sessions/session", session: @study_session %></div>
<% end %>
<% end %>
<%= turbo_stream.update "#{@study_session.topic_id}_new_study_session", "" %>
<%= turbo_stream.update "flash", partial: "shared/flash" %>
Ending a session is the interesting one. Clicking "End this session" sends a PATCH to our complete action, which answers with update.turbo_stream.erb:
<%# app/views/study_sessions/update.turbo_stream.erb %>
<%= turbo_stream.update dom_id(@study_session) do %>
<div class="mb-2"><%= render "study_sessions/session", session: @study_session %></div>
<% end %>
<% if @study_session.topic.study_sessions.active.empty? %>
<%= turbo_stream.update "#{@study_session.topic_id}_new_study_session" do %>
<%= link_to "Start a study session", new_study_session_path(topic_id: @study_session.topic_id) %>
<% end %>
<% end %>
<% if @study_session.finished_at %>
<%= turbo_stream.remove "active_#{@study_session.id}" %>
<%= turbo_stream.append "completed_sessions" do %>
<p><%= @study_session.topic.study_plan.name %> - <%= @study_session.topic.name %></p>
<div><%= render "study_sessions/session", session: @study_session %></div>
<% end %>
<% end %>
<%= turbo_stream.update "flash", partial: "shared/flash" %>
Look at what a single click does: the session row changes to "Completed", the "Start" link comes back, the session leaves the dashboard's "Active" list and joins "Completed Today", and a notice appears. Four changes, zero JavaScript.
A useful detail: a stream that targets an id that isn't on the page does nothing, and raises no error. The same template runs when you end a session from the study plan page, where active_… and completed_sessions don't exist, and those two actions are simply skipped. We'll lean on this behavior in Part 8, when the server will push streams to pages the user never clicked on.
Here is the controller action that triggers it:
def complete
if @study_session.update(finished_at: Time.current)
respond_to do |format|
format.turbo_stream do
flash.now[:notice] = "Study session completed successfully."
render :update
end
format.html { redirect_to study_plan_path(@study_session.study_plan), notice: "Study session completed successfully." }
end
else
flash.now[:alert] = @study_session.errors.full_messages.join(", ")
render :edit, status: :unprocessable_content
end
end
render :update reuses the update template, since "complete" and "update" produce the same change on the page.
✅ How to test this
Manual checks:
- Open the study plan page, then open DevTools → Network. Click "Add a Topic" and submit. You'll see two requests, and the submit response has the content type
text/vnd.turbo-stream.html. Click the response tab to see the<turbo-stream>tags. - Note the scroll position and the other topics' state: nothing resets.
- Submit a topic with a blank name (remove
requiredin DevTools if needed). The error should appear inside the form area. - Turn JavaScript off in the browser and repeat. The app falls back to regular redirects.
Automated tests. Turbo ships test helpers. Add to test/controllers/topics_controller_test.rb (using the setup from Part 4):
test "create answers with turbo streams" do
assert_difference -> { @plan.topics.count }, 1 do
post topics_path,
params: { study_plan_id: @plan.id, topic: { name: "Joins", estimated_hours: 3 } },
as: :turbo_stream
end
assert_response :success
assert_turbo_stream action: :append, target: "topics"
assert_turbo_stream action: :update, target: "new_topic"
assert_turbo_stream action: :update, target: "flash"
end
test "create falls back to a redirect for plain HTML" do
post topics_path, params: { study_plan_id: @plan.id, topic: { name: "Joins", estimated_hours: 3 } }
assert_redirected_to study_plan_path(@plan)
end
test "destroy removes the topic's element" do
topic = @plan.topics.create!(name: "Joins", estimated_hours: 3)
delete topic_path(topic), as: :turbo_stream
assert_turbo_stream action: :remove, target: "topic_#{topic.id}"
end
test "an invalid topic re-renders the form with an error" do
post topics_path, params: { study_plan_id: @plan.id, topic: { name: "", estimated_hours: 3 } }
assert_response :unprocessable_content
assert_select "turbo-frame#new_topic", text: /can't be blank/
end
And one for sessions:
test "completing a session updates the page with streams" do
topic = @plan.topics.create!(name: "Joins", estimated_hours: 3)
session = topic.study_sessions.create!(title: "Read chapter 1")
patch complete_study_session_path(session), as: :turbo_stream
assert_turbo_stream action: :update, target: "study_session_#{session.id}"
assert_turbo_stream action: :remove, target: "active_#{session.id}"
assert_turbo_stream action: :append, target: "completed_sessions"
assert session.reload.finished_at.present?
end
The failing-form test uses a plain request on purpose. With as: :turbo_stream, the request would accept only streams, and render :new (an HTML template) would have nothing to render. Real Turbo form submissions also accept HTML, which is why the browser works.
Browser-driven tests of this behavior (clicking and seeing the page change) come in the testing post (Part 13).
Common mistakes
-
"Content missing" in a frame. The response has no
<turbo-frame>with the id of the frame you clicked in. Check both ids match exactly, includingdom_idvs a hand-typed string. -
Form submits and nothing happens. A failed form rendered with a 200 status. Add
status: :unprocessable_content. - Error messages vanish. They sit outside the frame. Put them inside it.
- Stream does nothing. The target id isn't on the page (typo, or an element wrapped in the wrong place). Turbo doesn't complain, so check the id in DevTools.
-
Missing template for
turbo_stream. The template must be namedaction.turbo_stream.erb, and the action must notrendersomething else first. -
Redirect after
DELETEreplaysDELETE. Usestatus: :see_otheron that redirect. -
Using
flashwith a stream. It will show up again on the next request. Useflash.now.
Recap
- Turbo Drive speeds up every navigation by default.
- A Turbo Frame swaps one region, matched by id.
- A Turbo Stream sends several precise updates (
append,update,remove, …) in one response. -
respond_tolets one action serve Turbo and plain HTML. -
dom_id,turbo_frame_tagandflash.noware the three helpers you'll use most.
Next up
Our app is fast, but it all happens when you click. In Part 6 we'll make Study Flow do work on its own: background jobs with Active Job and Solid Queue, so the app can remind you to study even when no one is looking.
Top comments (0)