Turbo Streams In Rails | How to use turbo streams in rails?
In Rails 7, hotwire is the default front-end framework, this means we don't need to install additional gems to the application. It is used to send HTML over the wire. It is a collection of tools that simplifies building web applications in Rails, without relying heavily on Javascript. It sends HTML over the wire instead of JSON like traditional single-page applications (SPAs).
TURBO STREAMS:
It is used to add real-time update features to the applications. It helps to add real-time features using CRUD actions. Ok so let's start using the turbo streams in our application.
Create a new application in rails
- rails new railshotwire
Create a Product model:
- rails g model Product name:string
- rails db:migrate
Create a `products` controller
- rails g controller Products
Within the products controller, define the create and index actions as follows:
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
@products = Product.all
end
def create
@product = Product.create(product_params)
end
private
def product_params
params.require(:product).permit(:name)
end
end
Define routes for products
# config/routes.rb
- resources :products, only: [:index, :create]
Next, let's create the index.html.erb file and insert the following code into it.
# app/views/products/index.html.erb
<%= form_with scope: :product, url: products_path do |f| %>
<%= f.label :name, "Product name" %><br>
<%= f.text_field :name %>
<% end %>
<h1>Products Lists</h1>
<turbo-frame id="products">
<% unless @products.empty? %>
<% @products.each do |product| %>
<%= product.name %><br>
<% end %>
<% end %>
</turbo-frame>
Proceed by creating the create.turbo_stream.erb file, and simply copy and paste the provided code snippet into it.
# app/views/products/create.turbo_stream.erb
<turbo-stream action="append" target="products">
<template>
<%= @product.name %><br>
</template>
</turbo-stream>
Run the server
- rails s
Discover the magic of real-time updates as you add a new product. No more waiting for page reloads—see your changes come to life instantly.
In this instance, we've employed the append action within the turbo-stream tag. However, it's worth noting that there are several other actions available, such as prepend, remove, replace, update, before, and after. These diverse actions offer flexibility to tailor our applications precisely to their requirements.
Comments
Post a Comment