Diving into Hotwire

Episode #277 by Teacher's Avatar David Kimura

Summary

In this episode, we look at the installation scripts of Hotwire and get a better understanding of what they're doing in order to integrate it into our applications more efficiently.
rails hotwire stimulusjs javascript 14:45

Resources

Download Source Code

Summary

# Terminal
bundle add hotwire-rails
bin/rails webpacker:install:stimulus
bin/rails turbo:install
rails g scaffold products title "price:decimal{8,2}"

# models/product.rb
class Product < ApplicationRecord
  validates :title, presence: true, uniqueness: true
end

# products/edit.html.erb
<%= turbo_frame_tag 'product' do %>
  <h1>Editing Product</h1>

  <%= render 'form', product: @product %>

  <%= link_to 'Show', @product %> |
  <%= link_to 'Back', products_path %>
<% end %>

# products/index.html.erb
<%= turbo_frame_tag 'product' do %>
  <h1>Products</h1>
  <table class='table'>
    <thead>
      <tr>
        <th>Title</th>
        <th>Price</th>
        <th colspan="3"></th>
      </tr>
    </thead>

    <tbody>
      <% @products.each do |product| %>
        <tr>
          <td><%= product.title %></td>
          <td><%= product.price %></td>
          <td><%= link_to 'Show', product %></td>
          <td><%= link_to 'Edit', edit_product_path(product) %></td>
          <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

  <br>

  <%= link_to 'New Product', new_product_path %>
<% end %>

# products/new.html.erb
<%= turbo_frame_tag 'product' do %>
  <h1>New Product</h1>

  <%= render 'form', product: @product %>

  <%= link_to 'Back', products_path %>
<% end %>

# products/show.html.erb
<%= turbo_frame_tag 'product' do %>
  <p id="notice"><%= notice %></p>

  <p>
    <strong>Title:</strong>
    <%= @product.title %>
  </p>

  <p>
    <strong>Price:</strong>
    <%= @product.price %>
  </p>
  <%= link_to 'Edit', edit_product_path(@product) %> |
  <%= link_to 'Back', products_path %>
<% end %>