Use Select2 that can be searched in Ruby on Rails


Select 2 is useful in a JS library for using select tags that can be searched on the Ruby on Rails form. This article is an introduction to RubyGem select2-rails for incorporating Select 2 into Ruby on Rails.

🎃 Installation

Please add the following configuration and execute bundle install in terminal.

# Support Select 2
gem 'select2-rails'

😀 Configuration

Add the following setting to load select 2 JavaScript into app/assets/javascripts/application.js. Together, if you give the js-searchable class in HTML, you can make it available as a SELECT 2 tag.

//= require select2

$(document).ready(function(){
// Turn on js-selectable class so that it becomes SELCT 2 tag
$('.js-searchable').select2({
allowClear: true,
width: 200
// If you are using Bootstrap, please add `theme: "bootstrap"` too.
});
});

Add CSS of Select 2 to app/assets/stylesheets/application.css.

*= require select2

If you use Bootstrap, please add the following configuration too.

*= require select2-bootstrap

🏀 How to use

If you attach the js-searchable tag to HTML class of select tag in Ruby on Rails, it will act as a select box.

<%= f.select_tag :category_id, category_options, class: 'js-searchable' %>

You can also select multiple by adding multiple: true to the option.

<%= select :article, :tags, tags, { selected: selected_tags }, { multiple: true, name: 'article[tags]', class: 'form-control js-searchable' } %>

🎳 Supplement: Clear the value with JS

The following code clears the value set in Select 2 from JavaScript.

$('.js-searchable').val(null).trigger("change");

🗽 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!