Exploring the Magic of Rails Hotwire: A Hands-On Guide

Dejan Vujovic
2 min readMay 19, 2023

--

Rails Hotwire is a game-changer for building interactive web applications. It simplifies the process of creating real-time, reactive user interfaces by seamlessly integrating into the Ruby on Rails framework. In this blog post, I’ll guide you through the steps of setting up and using Rails Hotwire, exploring its key components: Turbo Drive, Turbo Frames, Turbo Streams, and Stimulus. So, let’s dive into the world of Rails Hotwire and unlock its magic!

Prerequisites:

Before we start, ensure that you have Ruby on Rails installed and a basic understanding of Ruby and Rails concepts.

Setting up a Rails Application with Hotwire:

  1. Create a new Rails application by running the following command in your terminal:
rails new hotwire-demo

2. Change into the application’s directory:

cd hotwire-demo

Exploring Turbo Streams:

Turbo Streams allow you to update specific parts of your page in real time without refreshing the entire page.

  1. Let’s start by creating a new controller and view. Run the following command:
rails generate controller Posts

2. Open the app/views/posts/index.html.erb file and replace its content with the following code:

<h1>Posts</h1>

<%= turbo_stream_from "posts" %>

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

<%= form_with model: Post.new, id: "new_post", data: { turbo_frame: "posts" } do |f| %>
<%= f.text_field :title %>
<%= f.submit "Create Post" %>
<% end %>

3. In the app/controllers/posts_controller.rb file, add the following code:

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

def create
@post = Post.create(post_params)
redirect_to posts_path
end

private

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

4. Open the app/views/posts/_post.html.erb file and replace its content with the following code:

<div id="<%= dom_id(post) %>">
<h3><%= post.title %></h3>
</div>

5. Run the Rails server using the command:

rails server

6. Visit http://localhost:3000/posts in your browser. You should see a list of posts.

7. Create a new post by entering a title and clicking “Create Post.” Notice how the new post is instantly added to the list without refreshing the page. Magic!

This is just the beginning! In the next sections, we’ll explore Turbo Frames, Turbo Drive, and Stimulus to enhance your Hotwire-powered Rails application. You can find the second part of this tutorial here.

--

--