Search code examples
ruby-on-railsmany-to-manyactiveadmin

ActiveAdmin filter: a has_many: through attribute


I want to filter an ActiveAdmin table on an attribute of a model that is linked through a has_many :foo through: :bar relationship.

For example, if a Book

has_many :borrowers, through: :book_checkouts

...how do I add a filter option on the ActiveAdmin page for Books to let the user filter on the borrower_id? (As a string; Our library has so many borrowers that using a Select here is unwieldy.)


Solution

  • Background

    In your ActiveAdmin page, you can add filters like so:

    filter :column_name_1
    filter :column_name_2
    

    So you'll create a create a new filter statement for borrowers, but default, it will create a select.

    filter :borrowers
    

    Solution

    So in order to tell it that you don't want to use a select, you have to modify the symbol you give it with what column in the association you want to filter by. So if you want to filter by the ID of the borrowers, you'll do this:

    # You specify as: :numeric to so ActiveAdmin knows to add 
    # filtering options for numbers. So when it renders on the page,
    # for the filter option it will display three options to filter by:
    # ID equals, is greater than, or is less than
    
    filter :borrowers_id, as: :numeric
    

    If you want to filter by another column that's a string, like a name, for example, you'll do the following:

    filter :borrowers_name, as: :string
    

    Note: I also noticed that is you don't specify the as: :type then ActiveAdmin won't recognize the filter and won't render anything for it.

    Assisted by answer from question: Active Admin - filter by presence of has_many association