我一直在按照这个示例指南 ( 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