Search code examples
ruby-on-railsjquery-select2select2-rails

Rails 5 and select2 error, select2 is not a function


I am trying to use the rails select2 gem, gem 'select2-rails' But when I try to use it with the following order import order, my browser complains that select2 is not a function. From what I have found this order should be correct.

javascripts/application.js

//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require select2-full
//= require_tree .

$(document).on('turbolinks:load', function() {
   console.log('(document).turbolinks:load')
   $("#estimation_patient_id").select2({
       theme: "bootstrap"
   });
});

Solution

  • You can use

    //= require rails-ujs
    

    OR

    //= require jquery_ujs
    

    not needed to both

    And modify like below

    (function($){
        $(document).on('turbolinks:load', function() {
           $("#estimation_patient_id").select2({
               theme: "bootstrap"
           });
        });
    }(jQuery));
    

    Remember it: sometimes //= require select2-full is not working but //= require select2 is working nicely with all requirements. I recommend to use //= require select2.