ActiveAdmin: filter by the number of children

In a Ruby on Rails application that is heavily dependent on ActiveAdmin, I have a Sponsor model that is linked to a sponsorship model. One sponsorcan sponsor many children, so one sponsorcan have many sponsorships.

What I would like to do is to filter the sponsors by the number of sponsorship services that they have on the sponsor index page. So, 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-talk, I want a filter that will do something in the following lines:

Sponsor.all.select { |sp| sp.sponsorships.count > 1 }

I found out that this is actually quite complicated. ActiveAdmins filters by default work with attributes of a specific model (or its child models), and not with custom methods, while I need to precisely filter a special method. Thus, this is a filter in ActiveAdmins combined view / controller sponsor.rb file:

filter :sponsorships_count, label: 'Sponsorships', as: :numeric

where is :sponsorships_countnot an attribute of the Sponsor model.

I tried using Ransacker (it seems some people succeeded with it ), but could not determine the correct syntax. Others had some luck defining the filters as custom filters (using as: customsyntax such as here and providing the model area name as the filter name), but this did not work for me (the application uses ActiveAdmin version 1.0.0.pre, which is reportedly not works with this approach).

Help someone?

+1
source share

Source: https://habr.com/ru/post/1569249/


All Articles