Advanced filters in ActiveAdmin

Use jQuery plugin Chosen for select boxes filters

The Chosen plugin aims to improve select boxes by adding search-based filtering. When a user clicks into a Chosen element, their cursor is placed in a search field. Users can select their choice just the same as a standard select element.

Integrate Chosen in active admin is pretty simple:

  • Add gem 'chosen-rails' in your gemfile
  • Configure Chosen adding some options (in app/assets/javascripts/active_admin/chosen.js.coffee):
    $ ->
        $('.chosen-filter').chosen
            allow_single_deselect: true
            width: '100%'
  • Include Chosen javascript assets in app/assets/javascripts/active_admin.js adding //= require chosen-jquery
  • Include Chosen stylesheet in app/assets/stylesheets/active_admin.css.scss adding @import "chosen";

Now you need to add the Chosen HTML class, in this case .chosen-filter, in formtastic select input.
Create a file config/initializers/active_admin/chosen_filter.rb and add:

module ActiveAdmin
  module Inputs
    class Formtastic::Inputs::SelectInput
      include FilterBase

      def extra_input_html_options
        {
          class: 'chosen-filter'
        }
      end
    end
  end
end

Chosen with multiple select

Another option offered by Chosen is multiple select. User-selected options are displayed as boxes at the top of the element and are always visible. They can be removed with a single click or using backspace. Chosen has in-line search that allows you to navigate through associations so easily.

Create config/initializers/active_admin/multiple_chosen_filter.rb and add:

module ActiveAdmin
  module Inputs
    class FilterMultipleSelectInInput < Formtastic::Inputs::SelectInput
      include FilterBase

      def input_name
        "#{super}_in"
      end

      def extra_input_html_options
        {
          class: 'chosen-filter',
          multiple: true
        }
      end
    end
  end
end

Active Admin will pick the most relevant filter based on the attribute type. You can force the type by passing the :as option. In this case you need to use multiple_select_in to apply FilterMultipleSelectInInput class above.

Here’s an example of filter definition:

filter :country_id, label: 'Country', as: :multiple_select_in,  collection: -> { Country.all }

Overriding input_name method we configure ransack predicate. In this case we search all selected elements. Predicates are used within Ransack search queries to determine what information to match.
Ransack predicates can be found here.

Leave a Reply

wpDiscuz