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'
You can do it by defining before_filter
before_filter :only => [:index] do
if params['commit'].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
UPD:
in some cases you need to set filter if params[:q] is empty or params[:scope] empty
so this might work better
before_filter :only => [:index] do
if params['commit'].blank? && params['q'].blank? && params[:scope].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With