ruby-on-rails

ActiveAdmin: Custom column and its filter

Follow me
Follow me

Latest posts by Tomasz Antas (see all)

May 8, 2015

Article presents how to add custom column to table in index view and add custom filter for this column.

 

Introduction

Let’s assume that the Restaurant model exists and is registred in ActiveAdmin dashboard. Each restaurant can add an own logo (or just some image) for its profile (I’ve used Paperclip for this purpose). Index page contains a list of restaurants with some details, but it’s not necessary to display logos (or images) on index page. But it would be nice to see which restaurants didn’t upload logos and profiles are not completed. Whatsmore, it would be great to filter it.

 

Create custom column

We don’t use any additional column to mark if the logo was uploaded or not. We need only check if any url to image is stored under logo_file_name (it’s column added by Paperclip – tool to uploading and managing iamges). If logo_file_name is empty (nil / null) that the logos wasn’t added.

 

Create custom filter

Firstly, we add a custom filter to admin/restaurant.rb:

The next thing is to create a custom filter method. Add following to models/restaurant.rb:

And that’s it!

 

Clarification

Filter uses a ransacker (more info here).

Notice that ransacker in model/restaurant.rb uses containing_logo and filter in admin/restaurant.rb uses containing_logo_in (in is a suffix – more about available suffix here).

is a parameter passed from filter from admin/restaurants.rb. In this case it can be only true or false, because the declared collection is:

In if-conditional structure we check what is and the filter get restaurants containing logos (if v = true) or not containing (if v = false).

parent.table indicates to database table for this model and we point that we want use id to filter records.

Everything may generates such a query to database (if only restaurants with ids and contain a logos):

 

Resources:

Very helpful for me to create this post: http://nikhgupta.com/code/activeadmin/custom-filters-using-ransacker-in-activeadmin-interfaces/

Ransack: https://github.com/activerecord-hackery/ransack

MetaSearch (used by Ransack): https://github.com/activerecord-hackery/meta_search

 

Tomasz AntasActiveAdmin: Custom column and its filter