'ActiveAdmin - Filter with default value

Would like to know is that possible to have filter with default value with active admin? This will be helpful for preloading the data for the admin user.

filter  :country, :default=>'US'


Solution 1:[1]

Adapted Fivells answer to work correctly with scopes and downloads. Feels hacky but seems to do the job. Annotated intention in comments.

  before_filter only: :index do
    # when arriving through top navigation
    if params.keys == ["controller", "action"]
      extra_params = {"q" => {"country_eq" => "US"}}

      # make sure data is filtered and filters show correctly
      params.merge! extra_params

      # make sure downloads and scopes use the default filter
      request.query_parameters.merge! extra_params
    end
  end

Solution 2:[2]

Fixing issue with "Clear Filters" button breaking, updated answer building on previous answers:

Rails now uses before_action instead of before_filter. It belongs in the controller like so:

ActiveAdmin.register User do
  controller do
    before_action :set_filter, only: [:index]

    def set_filter
      # when arriving through top navigation
      if params.keys == ["controller", "action"]
        extra_params = {"q" => {"country_eq" => "US"}}

        # make sure data is filtered and filters show correctly
        params.merge! extra_params

        # make sure downloads and scopes use the default filter
        request.query_parameters.merge! extra_params
      end
    end
    params.delete("clear_filters") #removes "clear_filters" if it exists to clear it out when not needed
  end
end

Note, ActiveAdmin uses ransack for queries (ex. {"q" => {"country_eq" => "US"}}), check out https://activerecord-hackery.github.io/ransack/getting-started/search-matches for more matches if you need something more complex than "_eq".

Also, previous answers leave the "Clear Filters" button broken. It doesn't clear the filters, the filters set here are simply re-applied.

To fix the "Clear Filters" button, I used this post as a guide How to keep parameters after clicking clear filters in ActiveAdmin.

#app/assets/javascripts/active_admin.js
# Making clear filter button work even on pages with default filters 
    
    $ ->
      $('.clear_filters_btn').click ->
        if !location.search.includes("clear_filters=true")
          location.search = "clear_filters=true"

This removes all search params (ie filters) and adds "clear_filters=true" so the controller can tell the request came from the "Clear Filters" button.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivo Dancet
Solution 2