simple_form select 集合由 AJAX 调用填充

simple_form select collection populated by AJAX call

在我看来,我有一个包含两个 select 列表的简单表单:

<%= simple_form_for @job, url: jobs_path do |f| %>
  <%= f.input_field :types, as: :select, collection: @types, id 'types-select' %>
  <%= f.input_field :subtypes, as: :select, collection: @subtypes %>
<% end %>

当用户 select 从第一个列表中选择一个选项时,下面的第二个列表应该使用基于上述 selection 的数据库中的值填充。

出于这个原因,当用户 select 从第一个列表中选择一个选项时,我会发出 ajax 请求:

$('#types-select').change(function(){
  $.ajax({
    url: '/subtypes',
    dataType: 'json',
    type: 'GET',
    data: {
      type_id: this.value
    },
    success: function(data) {
      console.log(data);
    }
  });
});

控制器看起来像这样:

class SubtypesController < ApplicationController
  respond_to :json

  def index
    @subtypes = Type.find(params[:type_id]).subtypes
    render json: @subtypes
  end
end

此时我如何用 @subtypes 中的选项填充第二个 select?

您可以在 success 回调中填充第二个下拉列表。确保 @subtypes 也以正确的 json 格式返回。

控制器:

  def index
    @subtypes = Type.find(params[:type_id]).subtypes
    render json: @subtypes.map { |item| { value: item.value } }  
  end

JS:

  $.ajax({
    url: '/subtypes',
    dataType: 'json',
    type: 'GET',
    data: {
      type_id: this.value
    },
    success: function(data) {
      // Populate second dropdown here
      var output = '';
      $subtypes.empty().append(function() {
        data.forEach(function(item) {
           output += "<option>" + item.value + "</option>"
        });
        return ouput;
      });
    }
  });