Rails7 stimulusを使用してTurboを使ってリアルタイム更新を実装する

  • 作成日 2024.07.09
  • rails
Rails7 stimulusを使用してTurboを使ってリアルタイム更新を実装する

Rails 7は、ユーザーインターフェースのリアルタイム更新を簡単に実現するための強力なツールであるTurboを提供しています。Turboは、ページ遷移を高速化し、リアルタイムのデータ更新を可能にするライブラリです。この記事では、Rails 7を使ってTurboを設定し、リアルタイム更新を実装する方法を紹介します。

環境

  • OS Ubuntu24.04
  • rails 7.1.3

Stimulusのインストール

Rails 7では、Stimulusがデフォルトでセットアップされているため、追加のインストールは不要ですが、念のため以下のコマンドで確認します。

$ bundle exec rails stimulus:install

モデルとコントローラーの作成

リアルタイムで更新するデータを扱うためのモデルとコントローラーを作成します。

$ rails generate model Post title:string content:text
$ rails db:migrate
$ rails generate controller Posts index create

Turboのセットアップ

Rails 7にはデフォルトでTurboが組み込まれています。特別な設定は不要ですが、必要に応じてGemfileを確認しましょう。

ビューの作成

リアルタイム更新を行うビューを作成します。

app/views/posts/index.html.erbを以下のように編集します。

<h1>Posts</h1>

<%= form_with(model: @post, local: false) do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.label :content %>
    <%= form.text_area :content %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

<div id="posts">
  <%= render @posts %>
</div>

app/views/posts/_post.html.erbを以下のように作成します。

<div id="<%= dom_id(post) %>">
  <h2><%= post.title %></h2>
  <p><%= post.content %></p>
</div>

コントローラーの編集

リアルタイム検索を実装するために、ProductsControllerを編集します。app/controllers/posts_controller.rbを以下のように編集します。

class PostsController < ApplicationController
  def index
    @post = Post.new
    @posts = Post.all
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      respond_to do |format|
        format.turbo_stream
        format.html { redirect_to posts_path, notice: "Post was successfully created." }
      end
    else
      render :index
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :content)
  end
end

Turbo Streamの設定

app/views/posts/create.turbo_stream.erbを以下のように作成します。

<%= turbo_stream.append "posts", partial: "posts/post", locals: { post: @post } %>

Railsサーバーの起動

最後に、Railsサーバーを起動して動作を確認します。
※自分の環境は外部からアクセスできるようにして起動してます。

$ rails s -b 0.0.0.0

ブラウザでhttp://localhost:3000/postsにアクセスし、検索フィールドに文字を入力してリアルタイム検索が正しく動作することが確認できます。