Cesare Ferrari

July 22, 2022

Rails Turbo frames: how to update a different frame


We have already seen that how to update a Turbo frame by clicking on a link. As long as the link is inside a turbo-frame element and the server response also contains a turbo-frame with the same id, Turbo Drive will update the first turbo-frame with the content of the second one.

But how do we update a different frame in the originating page?

We need to do three things:

  1. add a data-turbo-frame attribute to the frame containing the originating link, set to a different id value
  2. wrap the area of the page where we want the update to happen with a turbo-frame element with this id
  3. in the response page, create a turbo-frame, with the same id, that has the content we want to update
Here’s a code example.

First; we add a data-turbo-frame attribute to the originating link:

# app/views/welcome/index.html.erb

  <%= turbo_frame_tag "hello" do %>
    <%= link_to "Say Hello", "/hello",
        data: { turbo_frame: "greet" } %>
  <% end %>

Second: we add a new turbo-frame that will receive the new content, after the link is clicked:

# app/views/welcome/index.html.erb

  <%= turbo_frame_tag "greet" do %>
    <p>The new content should appear here</p>
  <% end %>

We add a turbo-frame to the response page, with the same id where we want the content to appear on the originating page:

# app/views/welcome/hello.html.erb  

  <%= turbo_frame_tag "greet" do %>    
    <p>Welcome to my site</p>  
  <% end %>

With this setup, when we click on the “Say Hello” link, we update the `turbo-frame` element with the `id` of greet with the text “Welcome to my site”.

As we can see, Turbo frames are a powerful tool in our Rails toolbox.

In these few posts, we have seen the basic functionalities of Turbo frames. In future posts we will explore how to set up Turbo frames according to Rails conventions and how to test views that contain Turbo frames.

Check out my site at www.ferrariwebdevelopment.com for more insights.