How to use Select2 with Ransack in Rails

I. Introduction:

We know that Select2 is a wonderful plugin to customize select box with support for searching, tagging, remote data sets and many other options. Otherwise, Ransack is a powerful tool for searching. It's possible to use both in Rails? That what I'll show you in this article.

II. Installation:

Add gems "ransack" and "select2-rails", including javascript assets and run bundle install


gem "ransack"
gem "select2-rails"


//= require select2


*= require select2

**III. Select2 using data remote: **

In this example, we create new product for a company which is selected from a select's box. Because the data for company is extremely big, it'll be greate if we can use both Select2 and Ransack.


<%= form_for Product.new, remote: true do |f| %>
  <%= f.label :company, t(".company") %>
  <%= f.select :company_id, [], {}, {class: "select-company"} %>
  <%= f.submit "Add" %>
<% end %>
<script type="text/javascript">
  <%= render "javascript.js" %>

For loading conpanies data, we use jQuery's AJAX methods. We can configure the way Select2 searched for remote data using the ajax option.


  ajax: {
    url: "/jsons/companies", //URL for searching companies
    dataType: "json",
    delay: 200,
    data: function (params) {
      return {
        search: params.term, //params send to companies controller
    processResults: function (data) {
      return {
        results: data
    cache: true

IV. Ransack and json result

We can just use the simple mode of Ransack for searching company'name when users fill the input's field in companies's selectbox.


resources :companies, only: :index


class CompaniesController < ApplicationController
  def index
    @companies = Company.actives.ransack(name_cont: params[:search].to_s.strip).result

In the view, we only need id and name of companies in select box, so we can use an json's array to return the result.


json.array! @companies do |company|
  json.id company.id
  json.text company.name

V. Conclusion:

Here a powerful method to select using Select2 and Ransack. I hope you find this article useful.

All Rights Reserved

Let's register a Viblo Account to get more interesting posts.