In a Ruby on Rails app that heavily relies on ActiveAdmin, I have a Sponsor model, which is associated with a Sponsorship model. One sponsor
can sponsor many children, so one sponsor
can have many sponsorships
.
What I would like to do, is to be able, on the Sponsor index page, to filter out sponsors by the number of sponsorships they have. So that, for example, I want to see only those sponsors who have more than one sponsorship, or less than five, and so on. You get the idea. In Ruby-speak, I want a filter that would do something along the following lines:
Sponsor.all.select { |sp| sp.sponsorships.count > 1 }
I found out that it is, in fact, quite hard to do. Default ActiveAdmin’s filters work on attributes of a particular model (or its children models), and not on custom methods, while I need to filter precisely by a custom method. So this is the filter in ActiveAdmin’s combined view/controller sponsor.rb file:
filter :sponsorships_count, label: 'Sponsorships', as: :numeric
where :sponsorships_count
is not an attribute of the Sponsor model.
I tried to use Ransacker (it seems some people have had success with it), but couldn't figure out the proper syntax. Others had some luck specifying filters as custom (using as: custom
syntax such as here and providing the name of a model scope as a filter name), but this didn't work for me (the app is using ActiveAdmin version 1.0.0.pre which is reported not to work with this approach).
Help, somebody?