Last Updated: February 25, 2016
·
3.42K
· macfanatic

State & Country Filters for ActiveAdmin

You might already know that if you name your attribute on a model :country that ActiveAdmin will attempt to use the wonderful country-select gem (required) to render the select list for you.

However, this tip is to get a country select, as well as a selection of US states, in the filters sidebar on the listing of a resource in ActiveAdmin.

First, create the following two files in your Rails project:

  1. /lib/active_admin/inputs/filter_country_input.rb
  2. /lib/active_admin/inputs/filter_state_input.rb

This assumes that in your Rails initializer that you have set the "autoload_paths" to "lib".

Now, in the country file, paste the contents of this gist. This will re-use the listing of countries that the country-select gem provided for us in the first place.

Next, in the state file, paste the contents of this gist. This will give you a drop down with long titles, expecting the 2 letter abbrev in your db. Remove the "invert" at the bottom of the file, or tweak the hash itself to suite your needs.

Restart your Rails server and you can use the following when registering your resources with ActiveAdmin:

ActiveAdmin.register User do
  filter :country, as: :country
  filter :state, as: :state
end