[RUBY] How to install JavaScript library "select2" that makes multiple selections of selectbox fashionable in Rails 6.0

Introduction

Hello everyone! I'm @hiroki_tanaka, the producer of Mayu Sakuma.

The other day, I have introduced select2, a plugin that makes multiple selections of selectbox fashionable in Rails 6.0 series. At that time, I was a little addicted to the difference from the introduction method up to Rails 5 series, so I summarized what I investigated.

Usage environment

What is select2

select2 is a JavaScript library that makes the HTML selectbox design fashionable. our official site is here. → select2 It is a plugin that allows you to easily implement not only a single-select selectbox UI but also a multi-select selectbox.

Sample on official website

--Before introducing select2 image.png

--Multiple selection pull-down after introducing select2 image.png

How to install in Rails 6.0

The introduction of select2 in Rails5 series was introduced using Gem, but from Rails 6.0, Webpacker is used instead of Gem. I would like to introduce the procedure one by one.

1. Introducing the library required for select2 with yarn

Execute the following command to install select2 in your Rails application. At this time, not only select2 but also jQuery (and popper.js) required to install select2 and bootstrap, which is the UI part of select2, will be installed.

$ yarn add jquery
$ yarn add popper.js
$ yarn add bootstrap
$ yarn add select2

2. Set to use jQuery / popper.js on Rails

Set the Rails application webpack / environment.js so that jQuery can be called from any Rails file.

config/webpack/environment.js


const { environment } = require('@rails/webpacker')

//To use jQuery and Bootstrap JS
const webpack = require('webpack')
environment.plugins.prepend(
    'Provide',
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        Popper: 'popper.js'
    })
)
module.exports = environment

Also, add JQuery to the packs / application.js manifest.

app/javascript/packs/application.js


require("jquery")

3. Set up bootstrap to be used on Rails.

Make the following two settings to enable bootstrap to be used in Rails applications.

app/javascript/packs/application.js


import 'bootstrap';
import '../stylesheets/application';

app/javascript/stylesheets/application.scss


@import '~bootstrap/scss/bootstrap';

4. Set the erb file to use webpacker.

Bootstrap installed in webpacker for all View files of Rails application ・ Set to the original layouts / application.html.erb so that jQuery can be used.

app/views/layouts/application.html.erb


<head>
<%= stylesheet_pack_tag "application", media: "all" %>
<%= javascript_pack_tag 'application' %>
</head>

5. Define selectbox on erb and describe in JS file to use select2.

Define a selectbox that makes multiple selections on the application's erb. At this time, if select_tag is set to multiple: true as an option, it becomes a selectbox that can be selected multiple times.

Then, write in the JS file corresponding to the erb file so that the corresponding selectbox uses select2.

app/views/test.html.erb


<%= javascript_pack_tag 'test' %>
<%= select_tag('animal', options_for_select([['Dog', 'dog'], ['Cat', 'cat'], ['Bird', 'bird'], ['Ushi', 'cow'], ['Snake', 'snake']]), class: "form-control", multiple: true) %>

app/javascript/packs/test.js


$(function () {
    $('#animal').select2();
});

6. Completed! !!

image.png

Bonus: Use option of select2

There are various options in select2. → select2 Options These options can be set with jQuery. The following is an example of option settings.

app/javascript/packs/test.js


$(function () {
    $('#animal').select2({
        width: 'resolve' //Dynamically change the width according to the page size.
        theme: "classic" //Change to the classic UI.
        debug: true //Output debug messages to the browser console.
    });
});

in conclusion

I feel that the introduction of select2 has become easier by using yarn. However, I often don't understand the internal behavior of select2, so I would like to deepen my understanding.

Recommended Posts

How to install JavaScript library "select2" that makes multiple selections of selectbox fashionable in Rails 6.0
How to install Swiper in Rails
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
Summary of how to select elements in Selenium
[Rails] How to use select boxes in Ransack
How to use JQuery in js.erb of Rails6
[Ruby on Rails] How to install Bootstrap in Rails
[Rails] How to load JavaScript in a specific view
Install multiple submit buttons in Rails View to get the value of the pressed button
[Rails] How to install devise
Super easy in 2 steps! How to install devise! !! (rails 5 version)
[Rails] How to install simple_calendar
How to make th: value of select have multiple values
[Rails] How to install reCAPTCHA
How to delete large amounts of data in Rails and concerns
[Rails] How to install Font Awesome
[Rails] How to write in Japanese
How to install Bootstrap in Ruby
[Rails] How to install ImageMagick (RMajick)
[Rails] How to install Font Awesome
How to introduce jQuery in Rails 6
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to implement search functionality in Rails
How to use custom helpers in rails
How to name variables 7 selections of discomfort
How to insert a video in Rails
How to use MySQL in Rails tutorial
[rails] How to configure routing in resources
How to implement ranking functionality in Rails
How to publish a library in jCenter
How to use credentials.yml.enc introduced in Rails 5.2
How to execute multiple commands in docker-compose.yml
[Rails] How to register multiple records in the intermediate table with many-to-many association
How to resolve errors that occur in the "Ruby on Rails" integration test
[Rails] How to get rid of flash messages in a certain amount of time
How to make a unique combination of data in the rails intermediate table
[Rails] Introduction of pry-rails ~ How to debug binding.pry
How to install Titan2D (v4.2.0) in virtual environment
How to translate Rails into Japanese in general
How to prevent direct URL typing in Rails
How to separate .scss by controller in Rails
How to conditionally add html.erb class in Rails
[Rails] How to upload multiple images using Carrierwave
How to install multiple JDKs on Ubuntu 18.04 LTS
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to Install Oracle JDK 1.8 in Ubuntu 18.04 LTS?
How to make a follow function in Rails
How to define multiple orm.xml in Spring4, JPA2.1
How to specify index of JavaScript for statement
[Rails] How to use PostgreSQL in Vagrant environment
How to check Rails commands in the terminal
[Rails] How to search across columns of related models (parent or child) in ransack
How to deal with errors in Rails s could not find a JavaScript runtime.
[Rails] How to display the weather forecast of the registered address in Japanese using OpenWeatherMap