我在我的rails应用程序中使用tom-select(使用Stimulus)动态创建一个“Vendor”模型记录,然后在我的“Trx”模型的下拉列表中选择它。我可以获取创建记录的获取请求,但我的下拉列表没有更新。在12:14的时间点this SupeRails #17 video之后,他的网络选项卡显示2个项目:一个fetch,和一个xhr。在我的应用程序中,我只看到一个fetch项目(状态为200)。
我需要做些什么才能让下拉菜单填充新创建的记录?
下面是我的vendor_select_controller.js中TomSelect示例的设置:
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();
},
}
我的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
我的Trx表单中的Vendor collection_select字段:
<%= f.collection_select :vendor_id, Vendor.all, :id, :name, {:prompt => "Select Vendor"},
{class: "w-full", data: { controller: "vendor-select" } } %>
控制台日志的输出:
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)
1条答案
按热度按时间lawou6xi1#
与传递给
callback
函数的内容不匹配:它应该是什么:
也就是说,你也可以这样做: