Custom Filter in Active Admin — Part 1

Trisha Patel
1 min readMar 8, 2021

Active admin is my favourite plugin to build admin functionality using Ruby on Rails.

It is making developer life easy. Using active admin we can develop elegant and robust application with less code.

As we know AA is providing in-built filter functionality. Challenging part is to create custom filter if you have nested or polymorphic associations. There are different ways to achieve that.

Let’s assume you want allow admin to give comments on Products. Using active_admin_comments you can able to achieve that. I am not going into detail as our focus is creating custom filter for polymorphic associations.

Active admin is creating polymorphic association with model and referring as resource.

class Delivery < ApplicationRecord# Should return products that have comments  scope :product_list, ->{ where('products.id in (?)', Comment.where(resource_type: 'Product').pluck(:resource_id) }end

Filter code need to add in app/admin/active_admin_comments.rb

filter :resource_of_Product_type_id, label: ‘Product Name’, as: :select, collection: proc { Product.product_list }

In above example resource is a column name from active_admin_comments table as we are referring model which is mapped through resource. Product is the model name and id is the column to which we want to apply condition.

Another example

filter :resource_of_Product_type_category_id, label: 'Category Name',  as: :select, collection: proc { Product.by_category_id }

This will filter comments based on product category

Will discuss how to apply filter for nested relationship in Part - II.

--

--