RailsのHotwireとTurbo完全ガイド

RailsのHotwireとTurbo:完全ガイド

Hotwire (HTML Over The Wire) and Turbo are modern tools that simplify building dynamic, fast, and responsive web applications without writing much JavaScript. In this guide, we’ll explore how to implement Hotwire and Turbo in a Railsアプリケーション, complete with coding examples.

What is Hotwire and Turbo?

  • Hotwire: A framework for building modern web applications by sending HTML over the wire instead of JSON. It includes Turbo, Stimulus, and Strada.
  • ターボ: A core part of Hotwire that accelerates page navigation and form submissions by avoiding full-page reloads.

Setting Up Hotwire in Rails

Step 1: Add Hotwire to Your Rails App

Add the Hotwire gems to your Gemfile:

gem 'hotwire-rails'

Run the following commands to install Hotwire:
バンドルインストール

rails hotwire:install

This will install Turbo and Stimulus in your application.

Step 2: Enable Turbo Drive

Turbo Drive is enabled by default and speeds up page navigation by intercepting link clicks and form submissions. No additional setup is required.

Turbo Frames: Building Dynamic Components

Turbo Frames allow you to update specific parts of a page without reloading the entire page.

Example: Updating a Comment Section

  • Create a Turbo Frame
    Wrap the comment section in a Turbo Frame:
    <%= turbo_frame_tag "comments" do %>
    <%= render @post.comments %>
    <%終了%>
  • Add a Form Inside the Frame
    Include a form to add new comments:
    <%= turbo_frame_tag "new_comment" do %>
    <%= form_with model: [@post, Comment.new], data: { turbo_frame: "comments" } do |form| %>
    <%= form.text_area :content %>
    <%= form.submit "Post Comment" %>
    <%終了%>
    <%終了%>
  • Controller Action
    In your CommentsController, render the Turbo Frame after creating a comment:
    デフォルト作成
    @comment = @post.comments.create(comment_params)
    |format| を実行するための応答
    format.turbo_stream
    format.html { redirect_to @post }
    終わり
    終わり
  • Turbo Stream Response
    Create a create.turbo_stream.erb file to update the comments section:
    <%= turbo_stream.append "comments" do %>
    <%= render @comment %>
    <%終了%>

    <%= turbo_stream.replace "new_comment" do %>
    <%= render "form", post: @post, comment: Comment.new %>
    <%終了%>
  • Turbo Streams: Real-Time Updates
    Turbo Streams deliver real-time updates by sending HTML snippets over WebSockets or HTTP.

Example: Broadcasting New Comments

  • Set Up ActionCable
    Ensure ActionCable is enabled in your Rails app.
  • Broadcast New Comments
    In your Comment model, broadcast new comments after creation:
    クラス コメント < ApplicationRecord
    after_create_commit :broadcast_comment

    プライベート

    def broadcast_comment
    broadcast_append_to "post_#{post_id}_comments", partial: "comments/comment", locals: { comment: self }
    終わり
    終わり
  • Subscribe to Updates
    In your view, subscribe to the Turbo Stream:
    <%= turbo_stream_from "post_#{@post.id}_comments" %>
  • Stimulus: Adding Interactivity
    Stimulus is a lightweight JavaScript framework for adding behavior to HTML.

Example: Toggle Visibility

  • Create a Stimulus Controller
    Generate a Stimulus controller:
    rails generate stimulus toggle
  • Add the Controller Logic
    In app/javascript/controllers/toggle_controller.js:
    import { Controller } from "@hotwired/stimulus"
    export default class extends Controller {
    static targets = ["content"]
    toggle() {
    this.contentTarget.classList.toggle("hidden")
    }
    }
  • Use the Controller in Your View
    Add the controller to your HTML:
    <div data-controller="toggle">
    <button data-action="click->toggle#toggle">Toggle Content</button>
    <div data-toggle-target="content" class="hidden">
    This content is toggled!
    </div>
    </div>

結論

Hotwire and Turbo make it easy to build modern, dynamic Rails applications with minimal JavaScript. By leveraging Turbo Frames, Turbo Streams, and Stimulus, you can create fast, responsive, and interactive user experiences. If you’re looking for expert guidance on implementing these technologies, レイルスカルマ offers top-notch Rails開発サービス to help you build scalable and efficient applications. With Railscarma’s expertise, you can take your Rails projects to the next level while focusing on delivering exceptional user experiences.

関連記事

投稿者について

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


jaJapanese