Laura Diane Hamilton

Technical Product Manager at Groupon


How to Filter by Multiple Options with Filterrific

This was tested with Rails 4.1.4 and filterrific 1.3.1.

Let's say you want to allow the user to filter records via multiple checkboxes. For example, the user can select restaurants that cost either $ or $$, and cuisines either Mexican or Japanese.

Here is a tutorial explaining how to do that. I used the filterrific gem which provides support for filtering out of the box.

First, add a scope to your model. # app/models/restaurant.rb # Restaurant type selection scope :with_cuisine, lambda { |cuisines|   where(cuisine: [*cuisines]) }

(Note that in Rails 4 all scopes must use a callable object such as a Proc or Lambda.)

Second, enable filterrific for your class: class Restaurant < ActiveRecord::Base   belongs_to :business, foreign_key: 'business_id'   has_many :reviews   filterrific(     default_settings: { sorted_by: 'created_at_desc' },     filter_names: [       :sorted_by,       :search_query,       :with_cuisine     ]   ) ...

In your controller: # app/controllers/restaurant_controller.rb require 'builder' require 'will_paginate' include ActionView::Helpers::NumberHelper
class RestaurantController < ApplicationController   def list   end
  def index     @filterrific =, params[:filterrific])     @filterrific.select_options = {       sorted_by: Restaurant.options_for_sorted_by,       with_cuisine: Restaurant.options_for_select     }     @restaurants = Restaurant.filterrific_find(@filterrific).page(params[:page]).with_cuisines
    respond_to do |format|       format.html       format.js     end   end
  def reset_filterrific     # Clear session persistence     session[:filterrific_restaurants] = nil     # Redirect back to the index action for default filter settings.     redirect_to action: :index   end end

And in your view: <%# app/views/restaurants/index.html.erb %> <%= form_for @filterrific do |f| %> <div>   <h3>Select Cuisine:</h3>   <div class="row">     <% @filterrific.select_options[:with_cuisine].each do |c| %>       <div class="col-md-4">         <%= check_box_tag("filterrific[with_cuisine][]",c) %>         <%=h c %>       </div>     <% end %>   </div> </div> <% end %>

The [] after filterrific[with_cuisine] tells rails that it is looking for an array of attribute values. That is, find records containing any of the attributes in the array. If you omit the [] then it will only look at the last parameter value, which is not what you want. is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to