使用AJAX预填充Select2 - “找不到结果”

时间:2016-06-28 10:27:55

标签: jquery ruby-on-rails ruby-on-rails-4 jquery-select2 select2-rails

我一直在关注此示例指南(http://rails-select2-example.herokuapp.com/)以创建select2下拉列表,以便从我的数据库中搜索国家/地区。

但是,选择框始终显示为“No Results Found”。为什么不从js / ajax中获取值?

查看(new.html.erb)

          <select class="form-control" id="country_select">
          </select>

Controller(Searches_controller.rb)

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def new
        @countries = Country.all
        respond_with @countries
    end
end

的Javascript

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= user_searches_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });

路线

resources :users do
    resources :searches
  end

搜索迁移

class CreateSearches < ActiveRecord::Migration

  def change
      t.string :country
   end
      add_index :searches, [:user_id, :created_at]

  end
end

2 个答案:

答案 0 :(得分:1)

对于国内搜索,您可以直接使用Rails Helper Method

,而不是使用AJAX

见下面的例子:

application_helper.rb文件中创建一个方法:

def get_country
  Country.pluck(:name,:id)
end

在您的视图文件中:

<%= f.select :country_select, get_country, {prompt: 'Select Country'} %>

最后,添加js代码如下:

$("#country_select").select2({
  placeholder: "Select Country"
});

答案 1 :(得分:1)

由于您已在新操作中编写了代码,因此您调用的网址错误, 如果你想通过新动作打电话,

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def new
        @countries = Country.all
        respond_with @countries
    end
end

要么像这样更改ajax调用中的url,

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= new_user_search_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });

或者将代码更改为索引操作,

class SearchesController < ApplicationController
before_action :require_user
respond_to :html, :json

    def index
        @countries = Country.all
        respond_with @countries
    end
end

然后,您可以使用您的网址

  $('#country_select').select2({
    theme: "bootstrap",
    ajax: {
      url: "<%= user_searches_path(format: 'json') %>",
      dataType: "json",
      results: function(data, page) {
        return { results: $.map( data, function(country, i) { 
          return { id: country.id, text: country.name } 
        } ) }
      }
    }
  });