filteractiveadminmeta-search

Active admin "AND" filter with check boxes


I have simple active admin filter in my Parent resource:

filter :child_id, :as => :check_boxes, :collection => proc { Child.all }
filter :child_id_not, :as => :check_boxes, :collection => proc { Child.all }

I want to get all Parent resources that are or not associated with Child resource (has_and_belongs_to_many). Works not bad, but when I select for example two childs in first filter active admin returns all Parent resources that are associated with first one OR the second one. I need "AND" operator for both (:child_id and :child_id_not).

Any workarounds?


Solution

  • You will have to roll out your own scopes. ActiveAdmin uses meta_search for its filters (https://github.com/ernie/meta_search).

    In your admin file:

    filter :child_id_all,
      :as => :check_boxes,
      :collection => proc { Child.all }
    
    filter :child_id_all_not,
      :as => :check_boxes,
      :collection => proc { Child.all }
    

    In your parent model:

    scope :child_id_all_in, -> ids {
      ids.reduce(scoped) do |scope, id|
        subquery = Parent.select('`parents`.`id`').
          joins(:childs).
          where('`childs`.`id` = ?', id)
        scope.where("`parents`.`id` IN (#{subquery.to_sql})")
      end
    }
    scope :child_id_all_not_in, -> ids {
      ids.reduce(scoped) do |scope, id|
        subquery = Parent.select('`parents`.`id`').
          joins(:childs).
          where('`childs`.`id` = ?', id)
        scope.where("`parents`.`id` NOT IN (#{subquery.to_sql})")
      end
    }
    search_methods :child_id_all_in
    search_methods :child_id_all_not_in