57
loading...
This website collects cookies to deliver better user experience
Person
can have Awards
and Credits
and those awards and credits are what we'll display in our tabs.rails new hotwire_tabbing -T
cd hotwire_tabbing
rails g scaffold Person name:string
rails g model Credit name:string person:references
rails g model Award name:string person:references
rails db:migrate
rails s
class Person < ApplicationRecord
has_many :awards
has_many :credits
end
rails c
in your terminal), create a couple of Awards and Credits with the Person you created in the UI. We won't be covering creation of these resources in this lesson.Person.first.awards << Award.create(name: "Best Director")
Person.first.credits << Credit.create(name: "Star Wars - The good one")
hotwire-rails
to your Gemfile and then running bundle install
from your terminal. If you prefer, bundle add hotwire-rails
from your terminal works too.rails hotwire:install
from your terminal. Hotwire is now installed and you're ready to start building.rails g controller Awards
rails g controller Credits
Rails.application.routes.draw do
resources :people do
resources :awards, only: %i[index]
resources :credits, only: %i[index]
end
end
class AwardsController < ApplicationController
before_action :set_person
def index
respond_to do |format|
format.html { render partial: 'awards/list', locals: { awards: @person.awards, person: @person }}
end
end
private
def set_person
@person = Person.find(params[:person_id])
end
end
touch app/views/awards/_list.html.erb
<%= turbo_frame_tag "details_tab" do %>
<div>
<%= render partial: "shared/tabs" %>
<div>
<h3>Awards won by <%= person.name %></h3>
<ul>
<% awards.each do |award| %>
<li><%= award.name %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
turbo_frame_tag
which will turn into a <turbo-frame>
HTML element when this view renders. The turbo frame helper provided by hotwire-rails requires an id argument ("details_tab" in our case) which Turbo uses to make DOM updates as needed.mkdir app/views/shared
touch app/views/shared/_tabs.html.erb
<div>
<%= link_to "Awards", person_awards_path(@person) %><br />
<%= link_to "Credits", person_credits_path(@person) %>
</div>
touch app/views/credits/_list.html.erb
<%= turbo_frame_tag "details_tab" do %>
<div>
<%= render partial: "shared/tabs" %>
<div>
<h3>Credits for <%= person.name %></h3>
<ul>
<% credits.each do |credit| %>
<li><%= credit.name %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
class CreditsController < ApplicationController
before_action :set_person
def index
respond_to do |format|
format.html { render partial: 'credits/list', locals: { credits: @person.credits, person: @person }}
end
end
private
def set_person
@person = Person.find(params[:person_id])
end
end
app/views/people/show.html.erb
like this:<div>
<h2><%= @person.name %></h2>
<div>
<%= render partial: "awards/list", locals: { person: @person, awards: @person.awards } %>
</div>
</div>
<turbo-frame>
that our list partials render.