How to use Select2 with Ransack in Rails
This post hasn't been updated for 8 years
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
Gemfile
gem "ransack"
gem "select2-rails"
app/assets/javascripts/application.js
//= require select2
app/assets/stylesheets/application.css
*= 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.
app/views/products/new.html.erb
<%= 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" %>
</script>
For loading conpanies data, we use jQuery's AJAX methods.
We can configure the way Select2 searched for remote data using the ajax
option.
app/views/products/_javascript.js
$(".select-company").select2({
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.
config/routes.rb
resources :companies, only: :index
app/controllers/companies_controller.rb
class CompaniesController < ApplicationController
def index
@companies = Company.actives.ransack(name_cont: params[:search].to_s.strip).result
end
end
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.
app/views/companies/index.json.jbuilder
json.array! @companies do |company|
json.id company.id
json.text company.name
end
V. Conclusion:
Here a powerful method to select using Select2 and Ransack. I hope you find this article useful.
All Rights Reserved