Adding Interactivity with Turbo Frames
Adding Functionality in the App Using Turbo Frames
We’re now going to add new functionality to our app’s schedule page. We’ll allow a user to edit concert data inline on the schedule page. When users hit the “Edit” button, the display is replaced by a form, and when they hit the “Submit” button on the form, the updated data appears.
We’re not going to worry about authentication here. If you are using the existing code, the sign-in links work and you can sign in with the email
email@example.com the password
Note: You might have to refresh the page or click the “North By” link after logging in with an email if you’re executing the app using our platform. It will redirect you to the homepage after login into your local setups.
This is not a coding error, it is just a routing blocker.
A Turbo Frame is a custom HTML tag,
<turbo-frame>, that wraps part of our page and captures navigation. Within a Turbo Frame, clicking any links or submitting any forms will, by default, capture the server response, look for a Turbo Frame in that response with the same ID, and redraw only that Turbo Frame with the new Turbo Frame portion of the response. To put it another way, Turbo Frames allows a small part of the page to behave the way Turbo Drive treats the entire page.
Let’s see an example.
The display of a single line of concert data is managed by a partial at
app/views/concerts/_concert.html.erb. To wrap the entire partial, add this line to the top:
<%= turbo_frame_tag(dom_id(concert)) do %>
And close it with
<% end %>.
Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.
turbo_frame_tag method is a helper added by the
turbo-rails gem and is available anywhere in Rails views. It generates a
<turbo-frame> custom HTML element with the contents coming from the block, similar to many other Rails tag-building helper methods.
We’ll do the same thing with the
app/views/concerts/_form.html.erb partial. The new first line is
<%= turbo_frame_tag(dom_id(concert)) do %> and the new last line is
<% end %>. The edit and display partial Turbo Frames have the same DOM ID, but that won’t cause a problem because they’ll never be on the page simultaneously.
Turbo frame controllers
ConcertsController, we need to change the behavior of a successful update to only return the part and not the entire page: