ruby-on-railsstimulusjstom-select

Tom-select created record doesn't update the dropdown options (Rails / Stimulus)


I'm using tom-select in my rails app (with Stimulus) to create a 'Vendor' model record on the fly in order to then select it in the dropdown of my 'Trx' model. I can get the fetch request to create the record but my drop down does not update. Following this SupeRails #17 video at time 12:14, his network tab shows 2 items: a fetch, and an xhr. With my app, I only see a fetch item (with status 200).

What do I need to do to get the dropdown to populate with the newly created record?

Here are the settings for my TomSelect instance, in my vendor_select_controller.js:

settings = {
      plugins: ['clear_button'],
      selectOnTab: true,
      valueField: 'id',
      labelField: 'name',
      searchField: 'name',
      sortField: { field: "name", direction: "asc" },
      create: function (input, callback) {
        const data = { name: input }
        const token = document.getElementsByName("csrf-token")[0].content;
        fetch('/vendors', {
          body: JSON.stringify(data),
          method: 'POST',
          dataType: 'script',
          credentials: 'include',
          headers: {
            "X-CSRF-Token": token,
            "Content-Type": "application/json",
            "Accept": "application/json"
          },
        }).then((response) => { return response.json() })
          .then((data) => { callback({ value: data.id, text: data.name }) })
      },
      onItemAdd: function () {
        this.setTextboxValue('');
        this.refreshOptions();
      },
    }

my VendorsController

class VendorsController < ApplicationController
...
  def create
    @vendor = Vendor.new(vendor_params)

    respond_to do |format|
      if @vendor.save
        format.html { redirect_to vendors_path }
        format.json { render json: @vendor }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @vendor.errors, status: :unprocessable_entity }
      end
    end
  end

the Vendor collection_select field in my Trx form:

<%= f.collection_select :vendor_id, Vendor.all, :id, :name, {:prompt => "Select Vendor"},
  {class: "w-full", data: { controller: "vendor-select" } } %>

Output from my console logs:

Started POST "/vendors" for 127.0.0.1 at 2023-04-14 16:18:43 -0700
Processing by VendorsController#create as JSON
  Parameters: {"name"=>"Pines8", "vendor"=>{"name"=>"Pines8"}}
  TRANSACTION (0.1ms)  begin transaction
  ↳ app/controllers/vendors_controller.rb:11:in `block in create'
  Vendor Create (0.3ms)  INSERT INTO "vendors" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "Pines8"], ["created_at", "2023-04-14 23:18:43.634246"], ["updated_at", "2023-04-14 23:18:43.634246"]]
  ↳ app/controllers/vendors_controller.rb:11:in `block in create'
  TRANSACTION (6.2ms)  commit transaction
  ↳ app/controllers/vendors_controller.rb:11:in `block in create'
Completed 200 OK in 12ms (Views: 0.3ms | ActiveRecord: 6.6ms | Allocations: 2695)

Solution

  • valueField: 'id',
                 ^
    labelField: 'name',
                 ^
    

    do not match what you are passing to callback function:

    callback({ value: data.id, text: data.name })
    //         ^               ^
    //     valueField      labelField
    //     id not found    name not found
    

    what it should be:

    callback({ id: data.id, name: data.name })
    //         ^            ^
    //     valueField    labelField
    

    which means, you can also do this:

    callback(data)