Search code examples
ruby-on-railsactiveadminformtastic

How to create a dynamically populated select (drop down) filter with ActiveAdmin (Formtastic)


I'm working on a web application based on Active Admin and am trying to understand how to create a select filter that is dynamically populated with all the unique values from a particular field.

From my understanding Active Admin uses Formtastic for these.

The scenario is countries and the code below from the resource works correctly and inserts Austria & France into the select.

But how do I this dynamically, as in, how do I go and query all the possible unique country options, and insert them into this collection?

filter :Country, :as => :select, :collection => ["Austria", "France"]

Should I do this work in the model first and then link to it in the resource?

Appreciate your help.

Thanks so much.

EDIT: Based on comments, I've now tried this, but it is erroring:

filter :Country2, :as => :select, :collection => proc { Country.all.collect {|country| country.name}.uniq }

Erorr message: uninitialized constant Country

FYI model name is Dailydeal

EDIT 2:

Here is the new working code

filter :Country, :as => :select, :collection => proc { Dailydeal.all.collect {|dd| dd.Country}.uniq }

Solution

  • If you have model Country and want to filter all its objects names, you can do something like following:

    filter :name, as: :select, collection: -> { Country.all.collect {|country| country.name}.uniq }
    

    -> is a new syntax for lambda. This will allow you to load only currently present country names.

    Another way (if you have a some static set of countries) to use constant:

    in model:

    COUNTRIES = ["Australia", "USA"] #whatsoever

    and then in activeadmin:

    filter :name, as: :select, collection: -> { Country::COUNTRIES } 
    

    EDIT

    Based on comments..

    filter :country, as: :select, collection: -> { Dailydeal.all.collect {|dd| dd.country}.uniq }
    

    UPDATE

    This solution (using pluck) is said to be more efficient:

    filter :country, as: :select, collection: proc { Product.pluck(:country).uniq.sort }