jquery - Pre populating Select2 using AJAX - "No Results Found" -
i've been following sample guide (http://rails-select2-example.herokuapp.com/) create select2 drop down search countries database.
however select box comes empty "no results found". why wont pick values js/ajax?
view (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 } } ) } } } });
routes
resources :users resources :searches end
searches migrate
class createsearches < activerecord::migration def change t.string :country end add_index :searches, [:user_id, :created_at] end end
instead of using ajax, search in country can directly use rails helper method
see below example :
in application_helper.rb
file create 1 method :
def get_country country.pluck(:name,:id) end
in view file :
<%= f.select :country_select, get_country, {prompt: 'select country'} %>
and lastly, add js code follows :
$("#country_select").select2({ placeholder: "select country" });
Comments
Post a Comment