Rails 7 + Hotwire (Turbo + Stimulus) = Modern web applications
Tags: ruby, rails, hotwire, tutorial
Published: 2022-11-24 12:20:29


![The turbo frames with their respective references.](https://cdn-images-1.medium.com/max/2260/1*m40NSs4t3k3-8mZ7KwYr3Q.png)
>  **tl;dr;** Let’s understand how we can migrate a scaffold generated by the command ‘bin/rails g scaffold Kit::Product name:string’, to an improved and performative screen. Inserting partial load and DOM manipulation writing a very little code in VanillaJS (“almost” without to write Javascript).

## Scaffold (Rails 7)

 1. Getting Started with Rails ([https://guides.rubyonrails.org/getting_started.html#creating-a-new-rails-project-installing-rails](https://guides.rubyonrails.org/getting_started.html#creating-a-new-rails-project-installing-rails))

 2. Generating the scaffold ([https://guides.rubyonrails.org/command_line.html#bin-rails-generate](https://guides.rubyonrails.org/command_line.html#bin-rails-generate)):
Using just one command you will generate all of these files: Model, Migration, Controllers, Routes, Tests, Helpers, and JSON.

```
    $ **bin/rails generate scaffold HighScore game:string score:integer**
        invoke  active_record
        create    db/migrate/20190416145729_create_high_scores.rb
        create    app/models/high_score.rb
        invoke    test_unit
        create      test/models/high_score_test.rb
        create      test/fixtures/high_scores.yml
        invoke  resource_route
         route    resources :high_scores
        invoke  scaffold_controller
        create    app/controllers/high_scores_controller.rb
        invoke    erb
        create      app/views/high_scores
        create      app/views/high_scores/index.html.erb
        create      app/views/high_scores/edit.html.erb
        create      app/views/high_scores/show.html.erb
        create      app/views/high_scores/new.html.erb
        create      app/views/high_scores/_form.html.erb
        invoke    test_unit
        create      test/controllers/high_scores_controller_test.rb
        create      test/system/high_scores_test.rb
        invoke    helper
        create      app/helpers/high_scores_helper.rb
        invoke      test_unit
        invoke    jbuilder
        create      app/views/high_scores/index.json.jbuilder
        create      app/views/high_scores/show.json.jbuilder
        create      app/views/high_scores/_high_score.json.jbuilder
```

After installing Rails, create your project, and generate your scaffold. Let's try to improve the default interface.

I am using the [Tailwind](https://tailwindcss.com/) to insert styles on the interfaces and the [ViewComponent](https://viewcomponent.org/) for “creating reusable, testable & encapsulated view components, built to integrate seamlessly with Ruby on Rails”.

You could see the resulting code at [https://github.com/raphox/rails-7-fullstack](https://github.com/raphox/rails-7-fullstack).

## Turbo (heart of Hotwire)
>  Hotwire is an alternative approach to building modern web applications without using much JavaScript by sending HTML instead of JSON over the wire.

You can see the unique application’s screen in the following image. Yes, this project has just one screen. Let’s try to be simple to focus on the most important things.

![The screen has a list of all products, a form filter, and a form to create and manage the products.](https://cdn-images-1.medium.com/max/2260/1*Ad3KVV2Q7Nuorl9o3NCq9w.png)

In this screen, we have two dynamic areas:

 1. List of products

 2. Form to create and edit the selected product

![The turbo frames with their respective references.](https://cdn-images-1.medium.com/max/2260/1*m40NSs4t3k3-8mZ7KwYr3Q.png)

I created a PR so you can see the exact part of the code that was changed or inserted to use the **Hotwire** on your project. You can see this PR on [https://github.com/raphox/rails-7-fullstack/pull/1](https://github.com/raphox/rails-7-fullstack/pull/1).

The unique screen on the system has a few triggers to call actions or make requests.

 1. Plus button to access the ‘kit/products/new’ page

 2. Search input field

 3. Products links to access the product’s edit page

 4. Buttons to update, remove or create products based on the form’s fields data

![The elements that are having their default behavior changed to interact with the turbo frames.](https://cdn-images-1.medium.com/max/2260/1*6rm4NVZ3vYM7NxbFPlvdVg.png)

Using the **Turbo**, we can override the **click** event of the plus button to request the HTML of a new product form from the backend and put it in the ‘product_form’ area.

You don’t need to write Javascript to override the events on your elements, just insert a new attribute ‘turbo_frame’ on your HTML tag. Like here:
{% gist https://gist.github.com/raphox/5c13a0accec72a854060eeb40d6e30b4.js %}
![The link to call route ‘new_kit_product’ is requesting the URL but its result is being put on the ‘turbo_frame#kit_product_form’.](https://cdn-images-1.medium.com/max/2260/1*JGjvmgpp_TehMDU0LpUMxg.png)

We can use the same approach of the plus button in the link of products and prevent reloading the entire screen HTML and assets.

![The links to call route ‘edit_kit_product’ is requesting the URL but its result is being put on the ‘turbo_frame#kit_product_form’.](https://cdn-images-1.medium.com/max/2260/1*eab3jmwE8ARV6ZP7WHnzng.png)

Now we need to use a little Javascript to insert the event ‘change’ to request a filtered list of products from the backend.

In my code, I insert the ‘turbo_frame’ attribute into the form to change the submit action making the request using Turbo. In the next topic, we can see how to use the Stimulus and Javascript controllers to change the event ‘change’ of the input.

![The form to call route ‘kit_products’ is requesting the URL but its result is being put on the ‘turbo_frame#list_kit_products’.](https://cdn-images-1.medium.com/max/2260/1*IOLs08X2xm8JtryG_xHULQ.png)

Now we will need to submit the form and refresh the list of products. But we can do this better. We know that the updated list has changed on the created/updated product. So, we need to update the list with this product, instead refresh and query all the list of products from the database. To do this we need to use a lot of the Javascript code or a few actions from the Stimulus.

You can see about the Javascript controller in the next topic.

![The form to call route ‘kit_product’ is requesting the URL but its result is being put on the ‘turbo_frame#kit_product_form’.](https://cdn-images-1.medium.com/max/2260/1*JJEGWr0-gPj-_hOJPujh8w.png)

## Stimulus (modest JavaScript framework)

You won’t see any difference. But the code savings and ease of integration will help you a lot when inserting new features.

The objective here is to insert an event on the search input form to make a request when the user changes the input’s value. When it occurs, the system will make a request to get all products filtered by the ‘name’ column. The result will be inserted into the list after it.

To implement the **Stimulus** in our current project, we need to follow the following steps:

**1.** Insert the attribute ‘**data-controller=”search-list”**’ to the wrapper with the form and the list of the products (app/components/search_list_component.html.erb line 1).
 — This attribute is responsible to relate the following code to the DIV element. Get more info here [https://stimulus.hotwired.dev/](https://stimulus.hotwired.dev/).
 — You can use the command ‘./bin/rails generate stimulus controllerName’ to generate the Javascript file with the class definition and import it in the ‘app/javascript/controllers/index.js’ automatically.
{% gist https://gist.github.com/raphox/ce5d03027ea99194561b97d15c80514d.js %}
**2.** Insert the attribute ‘**data-search_list_target=”inputSearch”**’ to the form search field (app/components/search_list_form_component.html.erb line 2).

**3.** Insert the action (**click->search-list#selectItem**) to activate the currently selected product (app/components/search_list_item_component.rb lines 20).

**4.** Insert the attribute ‘**search_list_target=”item”**’ to each item of the product list (app/components/search_list_item_component.rb lines 21).
{% gist https://gist.github.com/raphox/c39f5c7c07135affbd5d540638c43b7f.js %}{% gist https://gist.github.com/raphox/08eed2dd2889c100d420cbd5b73b523c.js %}
I am using [https://viewcomponent.org/](https://viewcomponent.org/) to define the view components instead to use a view or partial. Pay attention to this part [https://viewcomponent.org/#performance](https://viewcomponent.org/#performance).

I really liked having this structure in my project:
[**rails-7-fullstack/_list.html.erb at 11a479dafa5c84a1e769721d57792f39914a1204 ·…**](https://github.com/raphox/rails-7-fullstack/blob/11a479dafa5c84a1e769721d57792f39914a1204/app/views/kit/products/_list.html.erb#L23-L26)

This approach is very similar to the React components or other Javascript Frameworks.
{% gist https://gist.github.com/raphox/4d3d54f06cb30e59c5e92d90cd7f3466.js %}
I created a PR where you can see the exact part of the code I changed or inserted to use the **Stimulus** on my project. You can see this PR on [https://github.com/raphox/rails-7-fullstack/pull/2](https://github.com/raphox/rails-7-fullstack/pull/2).