Skip to content

how to handle error and redirect? #47

Open
@laptopmutia

Description

@laptopmutia

any examples?

so I have rails application with turbo and turbo stream
then I use stimulus js with request.js to send a patch request but I don't know how to handle the error

import { Controller } from "@hotwired/stimulus"
import onScan from "onscan.js"
import { patch } from "@rails/request.js";
export default class extends Controller {
  static values = {
    sellingId: Number
  }
  connect() {
    let sellingId = this.sellingIdValue
    onScan.attachTo(document, {
      suffixKeyCodes: [13], // enter-key expected at the end of a scan
      onScan: function (sCode, _) { // Alternative to document.addEventListener('scan')
        patch(`/sellings/${sellingId}/add-item`, {
          body: { "selling": { "inventory_id": sCode } },
          contentType: "application/json",
          responseKind: "turbo-stream"
        })
      },
    });
  }
}

here is my controller

  def add_item
    idnya = params.require(:selling).permit(:inventory_id)[:inventory_id]

    if idnya && @selling.update_entry(idnya)
      respond_to do |format|
        format.html { redirect_to selling_path(@selling), notice: "Item was successfully Added." }
        format.turbo_stream { flash.now[:notice] = "Item ditambahkan." }
      end
    else
      flash.now[:error] = "Item tidak ditemukan."
      render :show, status: :unprocessable_entity
    end
  end

I have tried to add this
format.turbo_stream { flash.now[:error] = "Item not found." }
it could render the flash message just fine

but I felt its wrong since its return 200 ok instead 422 error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions