jqueryruby-on-railsruby-on-rails-4jquery-select2select2-rails

Pre populating Select2 using AJAX - "No Results Found"


I've been following this sample guide (http://rails-select2-example.herokuapp.com/) to create a select2 drop down to search for countries from my database.

However the select box always comes back empty with "No Results Found". Why wont it pick up the values from 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 do
    resources :searches
  end

Searches Migrate

class CreateSearches < ActiveRecord::Migration

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

  end
end

Solution

  • Instead of using AJAX, for Search in country you can directly use Rails Helper Method

    See the below Example :

    In your application_helper.rb file create one method :

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

    In your View file :

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

    And Lastly, add js code as follows :

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