Saturday, October 1, 2022
HomeRuby On RailsHotwire Turbo Changing Rails UJS

Hotwire Turbo Changing Rails UJS


# Terminal
rails new template --skip-javascript
bin/rails g scaffold merchandise identify shade "value:decimal{8,2}" sku
bundle add faker
bundle add hotwire-rails
bin/rails hotwire:set up
# db/seeds.rb
100.instances do
  Product.create(
    identify: Faker::Lorem.phrase,
    shade: Faker::Shade.hex_color,
    value: Faker::Commerce.value,
    sku: Faker::Quantity.quantity(10)
  )
finish
# views/merchandise/index.html.erb
<% @merchandise.every do |product| %>
  <%= content_tag :tr, id: dom_id(product) do %>
    <td><%= product.identify %></td>
    <td><%= product.shade %></td>
    <td><%= product.value %></td>
    <td><%= product.sku %></td>
    <td><%= link_to 'Present', product %></td>
    <td><%= link_to 'Edit', edit_product_path(product) %></td>
    <td><%= link_to 'Destroy', product,
              information: {
                "turbo-method": :delete,
                controller: "affirmation",
                "confirmation-message-value": 'Are you positive?',
                motion: "affirmation#affirm"
              } %></td>
  <% finish %>
<% finish %>
# OPTIONS 1 - products_controller.rb
embrace ActionView::RecordIdentifier

def destroy
  @product.destroy
  respond_to do |format|
    format.html { redirect_to products_url, discover: "Product was efficiently destroyed." }
    format.json { head :no_content }
    format.turbo_stream { render turbo_stream: turbo_stream.take away(dom_id(@product)) }
  finish
finish
# OPTION 2 - products_controller.rb
def destroy
  @product.destroy
  respond_to do |format|
    format.html { redirect_to products_url, discover: "Product was efficiently destroyed." }
    format.json { head :no_content }
    format.turbo_stream {}
  finish
finish
# OPTION 2 - views/merchandise/destroy.turbo_stream.erb
<%= turbo_stream.take away(dom_id(@product)) %>
# app/belongings/javascripts/controllers/confirmation_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  static values = { message: String }

  affirm(occasion) {
    if (!(window.affirm(this.messageValue))) {
      occasion.preventDefault()
      occasion.stopImmediatePropagation()
    }
  }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments