rails通过ajax加载选择选项

Dev*_*vin 1 ajax jquery select ruby-on-rails

我有一个关于通过Ajax请求将数据加载到Rails中的select form_helper的问题.

现在,我有一个选择输入字段,在表单中加载大约8000个产品(按用户分组)

因此,完整的http请求和要加载的页面大约需要16秒.它希望页面加载,然后在我的选择输入字段中的选项通过ajax加载记录,使页面加载,直到所有产品都加载.

这是我的选择输入字段:

<%= f.grouped_collection_select(:original_serial_number, 
      @users, 
      :products,
      :display_name, 
      :serial_number, 
      :asset_tag_and_serial_number_and_model, include_blank: true) %>
Run Code Online (Sandbox Code Playgroud)

有关如何做到这一点的任何提示?

谢谢

Gus*_*ego 7

要通过ajax加载选择记录,我建议你通过json请求来完成.

因此,在您的视图中,您发送传递ID的触发请求:

 <script>
    $(document).ready(function() {

      $('#trigger_select').change(function() {
          $.ajax({
             url: "<%= remote_select_url %>", // this will be routed
             type: 'GET',
             data: {
               send_id: $("#yourIdContainer").val()
             },
             async: true,
             dataType: "json",
             error: function(XMLHttpRequest, errorTextStatus, error){
                        alert("Failed: "+ errorTextStatus+" ;"+error);
                    },
             success: function(data){
                // here we iterate the json result
                for(var i in data)
                {
                  var id = data[i].id;
                  var title = data[i].title;
                  $("#subject_select").append(new Option(title, id));
                }        

             }
           });
        });
      });
  </script>
Run Code Online (Sandbox Code Playgroud)

然后,您必须在routes.rb上路由remote_select操作

  get 'controller/action', :as => 'remote_select'
Run Code Online (Sandbox Code Playgroud)

你的控制器:

  def action
    #filter using id passed by ajax
    @your_model = Your_model.apply_your_filter(params[:send_id]) 
    render json: @your_model
  end 
Run Code Online (Sandbox Code Playgroud)