このサンプル ガイド ( 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