Let say you have a ‘repos’ controller with an index method
repos_controller.rb
class ReposController < ApplicationController
def index
@repos = Repo.all
end
end
You would probably have a views/repos/index.html.erb
that gets loaded initially when a user navigates to the page.
On this page, you want to have a list of all the repos and a form to create a new repo.
Just like if you were doing standard rails stuff, you would create a views/repos/new.html.erb
file with the shared form partial except, you would wrap the entire form in a turbo_frame_tag
.
views/repos/new.html.erb
<%= turbo_frame_tag "repo_form" do %>
<%= render partial: "repos/shared/form", locals: { repo: new_repo } %>
<% end %>
Now, back in your index.html.erb
file you’ll want to do something like this
views/repos/index.html.erb
...
<%= turbo_frame_tag "repo_form", src: new_repo_path %>
<%= turbo_frame_tag "repos_table" do %>
<% repos.each do |repo| %>
<%= render 'repos/repo', repo: repo %>
<% end %>
<% end %>
...
What you’re doing here is creating a turbo_frame that lazy loads the new.html.erb
file into it and also creating a “repos_table” turbo_frame container that holds all your “repos”.
Now, back to your repos_controller.rb
. You’ll want to make your create method like so
... some logic for creating
respond_to do |format|
format.turbo_stream {}
#add this as a fall back for browsers with no JS
format.html {}
end
and now create a views/repos/create.turbo_stream.erb
file with something like this
<%= turbo_stream.append "repos_table" do %>
<%= turbo_frame_tag dom_id(@repo) do %>
<%= render "repos/repo", repo: @repo %>
<% end %>
<% end %>
This will add your newly created “repo” to the end of your repos_table list, but you’ll probably want to make your partial have a turbo_frame as well like so
views/repos/_repo.html.erb (or however you have your repo partial named/organized)
<%= turbo_frame_tag dom_id(repo) do %>
...
your code
...
<% end %>
What’s going to happen now is when you create a repo, the POST request will hit your controller and look for your create.turbo_stream.erb
file by default. That file will process your turbo_stream and add (append) your new repo to you “repos_table” turbo_frame.
Your next step is to create an edit link and an update.turbo_stream.erb
file that basically does the same thing as your create.turbo_stream.erb
file, except it does turbo_stream.replace
instead because you are “replacing” the repo turbo_frame with an updated one.
Hope this helps