Skip to content

Instantly share code, notes, and snippets.

@spilth
Last active February 17, 2022 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spilth/5cd413d9ed81700b4a2ce3882026a0e4 to your computer and use it in GitHub Desktop.
Save spilth/5cd413d9ed81700b4a2ce3882026a0e4 to your computer and use it in GitHub Desktop.
Quick Turbo Frames Tutorial

Turbo Frames

Create a Rails Project

$ rails new turboframes -d postgresql
$ cd turboframes
$ bin/setup

Add Scaffodling for Books and Albums

$ rails generate scaffold book title author
$ rails db:migrate
$ rails generate scaffold album title artist
$ rails db:migrate

Add Homepage and Latest Controllers

$ rails generate controller home index
$ rails generate controller LatestAlbums index
$ rails generate controller LatestBooks index

Update Routes

config/routes.rb

root "home#index"

resources :albums
resources :books

resources :latest_albums
resources :latest_books

Update app/controllers/latest_books_controller.rb

class LatestBooksController < ApplicationController
  layout false

  def index
    @books = Book.order(created_at: :desc).limit(5)
  end
end

Update app/controllers/latest_albums_controller.rb

class LatestAlbumsController < ApplicationController
  layout false

  def index
    @albums = Album.order(created_at: :desc).limit(5)
  end
end

Create app/views/home/index.html.erb

<h1>Home</h1>

<%= turbo_frame_tag :latest_books, src: latest_books_path, target: :_top, loading: :lazy do %>
  <p>Loading...</p>
<% end %>

<%= turbo_frame_tag :latest_albums, src: latest_albums_path, target: :_top, loading: :lazy do %>
  <p>Loading...</p>
<% end %>
  • first argument is the ID of the frame
  • src specifies the path to load the contents from
  • target specifies that all links within the turbo frame should open up outside the turbo frame
  • loading with :lazy as an argument specifies to not load the turbo frame until it is in the viewport, potentially preventing unnecessary loading

Update app/views/latest_books/index.html.erb

<%= turbo_frame_tag :latest_books do %>
  <h2>Latest Books</h2>

  <ul>
    <% @books.each do |book| %>
      <li><%= link_to book.title, book %></li>
    <% end %>
  </ul>
<% end %>

Update app/views/latest_albums/index.html.erb

<%= turbo_frame_tag :latest_albums do %>
  <h2>Latest Albums</h2>

  <ul>
    <% @albums.each do |album| %>
      <li><%= link_to album.title, album %></li>
    <% end %>
  </ul>
<% end %>

Notes

TypeError: Module specifier, 'application' does not start with "/", "./", or "../".

https://github.com/rails/importmap-rails#expected-errors-from-using-the-es-module-shim

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment