ROR Application Development Tips

I'm Ruby on Rails developer. I love to share my experience, technical knowledge. I work at Crypex Technologies which is developing applications in ROR for more than a decade.

Rails Plugin for search, sort & filter data - Filterrific

What is filterrific?
‘filterrific’ gem is used for filtering the data only. It is a Rails Engine plugin that makes it easy to filter, search, and sort your ActiveRecord lists.

Ruby On Rails Gem Filterrific

Features of filterrific gem:

    • It Integrates with pagination
    • Filters can be reset to default settings
    • Makes heavy use of ActiveRecord Scopes
    • API option to use Filterrific with Rails API mode. Just use gem ‘filterrific’, require: ‘filterrific_api’ in your Gemfile
    • ActionController helpers to shuttle filter params from ActionView forms to ActiveRecord based models, and to return matching records back from ActiveRecord to ActionView
    • It depends on ActiveRecord scopes for building DB queries
    • Can be used for HTML/JS/JSON/XML response formats
    • It is used to run filter settings from a filter UI to the controller and ActiveRecord
    • It persists filter settings in the HTTP session or DB for saved searches

Dependencies:

What I need to do?

  • Need to define ActiveRecord Scopes
  • Need to build and style filter form and record lists

How to use it?

Let us assume that we want to show the lists of ‘Students’ that can be filtered by application’s users.

Step 1:

  • #Gem File
  • gem ‘filterrific’

Step 2:

Add Filterrific to ‘student’ model:

filterrific(
 default_filter_params: { sorted_by: 'created_at_desc' },
 available_filters: [
 :sorted_by,
 :search_query,
 :with_country_id,
 ]
 )
 # define ActiveRecord scopes for
 # :search_query, :sorted_by, :with_country_id

Step 3:

Use Filterrific in index method of StudentsController:

def index
 @filterrific = initialize_filterrific(
 Student,
 params[:filterrific]
 ) or return
 @students = @filterrific.find.page(params[:page])

respond_to do |format|
 format.html
 format.js
 end
 end

Step 4:

Here’s the lists of students’ data is showing in the view.
Lastly, the Filterrific ActionView API is used to create the views:

  • Basically it shows the list of matching records and the form to update filter settings via AJAX form submission
  • Also used to reset the filter settings

Source: http://www.cryptextechnologies.com/blogs/filterrific-rails-plugin-for-search-sort-filter-data