Using Select2 in Rails via Webpacker

_config.yml

Nothing could be easier than using select2 with webpacker. You don’t particularly need to use any ruby gems.

Here’s how:

  1. First ensure that you have webpacker installed and ready to go.

  2. Add select2

yarn add select2

  1. Create a javascript file to set it all up:
///select2setup.js
import $ from 'jquery'
import 'select2/dist/css/select2.css'
import 'select2'

/// if you don't have turnbolinks then use this:
//// document.addEventListener('DOMContentLoaded', () => { 
window.addEventListener('turbolinks:load', () => {
  $('.select2').select2({
    tags: true,
    tokenSeparators: [',', ' ']
  });
})
  1. Important that file into your application.js file:
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


require("packs/select2setup")
  1. Make sure your rails select helpers are ready to file by marking them as so:

We’ve used the select2 class to get things going:

  <div class="form-group">
    <%= form.label :user_ids %>
    <%= form.collection_select :user_ids, User.all, :id, :email, {include_blank: true}, multiple: true, class: "select2 form-control" %>
  </div>

Winning!

Written on February 27, 2020