/ rails

Active Admin - adding custom search(outside the resource model)

In ActiveAdmin, if your resource model is deriving some data from other models, using some kind of relationship(has_one or has_many).

In this scenarios where you want to search and filter the resource based on the data in its related table, you can follow below:

Suppose you have a model School, and a model Student, now you want to search or filter students based on the school name.

We can filter using join(:schools).where("schools.name like") or say an In Query which is inefficient.

Either way ActiveAdmin does not provide default filters based on your associations.

or taking the complex route here: https://github.com/gregbell/active_admin/issues/45

We can achieve this by a simple approach:

  1. When you write filter :first_name, if first\_name is a string, activeadmin  looks for a method first\_name\_contains inside the resource model. The method first\_name\_contains is provided using meta\_search gem.
    
  2. This is how filters work in AA, using the meta\_search gem. Now if we can define an equivalent method for search in model, we can achieve what we need. 
    
  3. Define filter :name_of_filter, and specify as string, so filter name would name_of_filter_contains.

  4. Now define this as a class method inside your model or as a scope, your query to fetch records.
    
  5. Now your custom search work as a normal filter in AA.
    

Code:

IN AA:

filter :last_name, :as => :string, :label => 'Last Name'

In Model:

def self.last_name_contains
end

Other important AA links:

For Filter: https://gist.github.com/rdj/1057991

For Adding Autocomplete for fields: https://gist.github.com/bbonamin/1258276

For Adding tokeninput to ActiveAdmin: https://gist.github.com/abhijitsinha/8b6871cfda555d305be8

Thanks