What is Happening by Adding Interactivity?

Let's see what will happen by adding interactivity in our application using Turbo frames.

What’s happening in the Code?

By putting our HTML inside the <turbo-frame> tag, we allow Turbo to control both the request to and the response from the server.

When we click the “Edit” button, we make a standard Rails GET request, in this case for the ConcertController#edit action. Rails handles this request normally for the most part. If we look in the browser network tab, we can see that the return value is the entire edit page, including the <h2>Editing Concert</h2> header. Turbo inserts a Turbo-Frame header into the request, and Rails recognizes it and optimizes accordingly by not rendering the layout in the return value. This is because the system assumes that the layout is not the part that the receiving Turbo Frame is interested in.

When the response comes back to the browser, Turbo intercepts it and looks for the part of the response that contains a Turbo Frame tag with the matching ID. This is why the Turbo Frame in the form of partial and one in the display partial had to have the same DOM ID. Turbo extracts that Turbo Frame from the response and replaces the existing Turbo Frame’s contents with that of the incoming response’s Turbo Frame.

Common errors in Turbo frame

If the incoming response does not contain a matching Turbo Frame, the existing Turbo Frame is replaced with blank contents. It seems to disappear, though we will get an error message in the console saying, “Response has no matching element.” If we get a link inside a Turbo Frame and it appears to vanish, check the Rails log to see if an error was thrown or check the “Network” tab on the browser inspector to see what is being returned. It’s likely we are not getting a Turbo Frame with a matching ID.

Get hands-on with 1200+ tech skills courses.