Search code examples
ruby-on-railsactiveadminformtasticransack

Create a custom string filter in ActiveAdmin that defaults to Contains and doesn't show a string filter choice drop down - Formtastic & Ransack


The default string filter in ActiveAdmin has a select the options of:

  • Contains
  • Equals
  • Starts with
  • Ends with

This shows a dropdown next to the string search where you are able to choose these options.

My requirement is to have the filter to use contains search condition BUT not show the drop down/select to do this. So it will just have an input box for search, with no select to choose contains.

I originally achieved this by creating a partial, but that was problematic as it was then unable to work with the other filters that ActiveAdmin provides. Here is an image of the partial:

enter image description here

My current thinking is to create a custom filter that does this.

So below is the standard code for the string filter in ActiveAdmin. How could this be modified to default to contains and not show the drop down? I've tried removing the filter options but that doesn't work. Any ideas?

ActiveAdmin uses Ransack and Formtastic

module ActiveAdmin
  module Inputs
    class FilterStringInput < ::Formtastic::Inputs::StringInput
      include FilterBase
      include FilterBase::SearchMethodSelect

      filter :contains, :equals, :starts_with, :ends_with

      # If the filter method includes a search condition, build a normal string search field.
      # Else, build a search field with a companion dropdown to choose a search condition from.
      def to_html
        if seems_searchable?
          input_wrapping do
            label_html <<
            builder.text_field(method, input_html_options)
          end
        else
          super # SearchMethodSelect#to_html
        end
      end

    end
  end
end

Solution

  • To remove the need for a predicate drop down, you can use the Ransack's string-based query interface. For example, if you have an ActiveRecord User class with an attribute name and you want a containing filter on it, you could do something like:

    ActiveAdmin.register User do
      filter :name_cont, label: 'User name'
    end
    

    This will generate:

    User name input field

    And it will search for Users containing the introduced input in its name