ActiveAdmin: Filter by count of child objects

天大地大妈咪最大 提交于 2019-12-23 22:32:28

问题


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?

来源:https://stackoverflow.com/questions/27663015/activeadmin-filter-by-count-of-child-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!