weixin_33724659 2016-06-13 02:36 采纳率: 0%
浏览 36

Rails Select 2不起作用

I use select2 to call an ajax search on my form. The form is unable to get response with my ajax, I tested at postman my Brand method, and it is able to return json, so I wonder if it is something wrong with my apllication.js or input? Previously I test with:

Sample input

<%= f.select :brand_id, Brand.all.collect {|x| [x.name, x.id]}, {include_hidden: false} %>

it is able search all data inside brand table.
products_controller.rb

  def brand
    @brands = Brand.select(:id, :name).where("name like :q", q: "%#{params[:q]}%")
    respond_to do |format|  
        format.json { render json: {brands: @brands.map { |e| {id: e.id, name: e.name} }}
      }
    end   end

input form

<%= f.hidden_field :brand_id, class: "brand-select", data: { source: dashboard_brand_path, placeholder: 'Search for a name' } %>

application.js

$( ".brand-select" ).select2({
    minimumInputLength: 1,
    placeholder: "Brand search",
    theme: "bootstrap",
    tags: [],
    ajax: {
        url: "/dashboard/brand",
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        id: function(obj) {
          return obj.id;
        },
        data: function (term) {
            return {
            q: params.term, // search term
            page: params.page
          };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        name: item.name,
                        id: item.id
                    }
                })
            };
        }
    },
});

Thank for helping

  • 写回答

1条回答 默认 最新

  • weixin_33712881 2016-06-13 14:36
    关注
    <%= f.hidden_field :brand_id, class: "brand-select", data: { source: dashboard_brand_path, placeholder: 'Search for a name' } %>
    

    You have Used hidden_field. I guess you should use

    <%= f.select :brand_id, Brand.all.collect {|x| [x.name, x.id]}, {include_hidden: false}, class: 'brand-select', placeholder: 'Search for a name' %>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波