0

我一直在按照这个示例指南 ( http://rails-select2-example.herokuapp.com/ ) 创建一个 select2 下拉列表来从我的数据库中搜索国家/地区。

但是,选择框总是以“未找到结果”返回为空。为什么它不能从 js/ajax 中获取值?

查看 (new.html.erb)

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

控制器(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
4

2 回答 2

1

由于您在新操作中编写了代码,因此您调用的 URL 是错误的,如果您想从新操作中调用,

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 } 
        } ) }
      }
    }
  });
于 2016-06-28T12:32:28.263 回答
1

而不是使用 AJAX,对于在国家/地区进行搜索,您可以直接使用 Rails Helper Method

请参阅以下示例:

在您的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"
});
于 2016-06-28T12:07:09.087 回答