Ruby on rails 由AJAX调用填充的简单表单选择集合

Ruby on rails 由AJAX调用填充的简单表单选择集合,ruby-on-rails,ajax,ruby-on-rails-4,select,simple-form,Ruby On Rails,Ajax,Ruby On Rails 4,Select,Simple Form,在我看来,我有一个带有两个选择列表的简单表单: <%= 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 %> <%

在我看来,我有一个带有两个选择列表的简单表单:

<%= 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 %>
控制器如下所示:

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:“/子类型”,
数据类型:“json”,
键入:“GET”,
数据:{
键入\u id:this.value
},
成功:功能(数据){
//在这里填充第二个下拉列表
var输出=“”;
$subtype.empty().append(函数()){
data.forEach(功能(项){
输出+=“”+item.value+“”
});
返回输出;
});
}
});

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

控制器:

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

$.ajax({
url:“/子类型”,
数据类型:“json”,
键入:“GET”,
数据:{
键入\u id:this.value
},
成功:功能(数据){
//在这里填充第二个下拉列表
var输出=“”;
$subtype.empty().append(函数()){
data.forEach(功能(项){
输出+=“”+item.value+“”
});
返回输出;
});
}
});
  $.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;
      });
    }
  });