Reputation: 11
How do I implement custom filtering in ActiveAdmin? It should be based on ActiveRecord conditions.
E.g. I have 2 models: Product and Category
class Product < ActiveRecord::Base
belongs_to :category
scope :in_category, ->(category_id) { where(category_id: Category.find(category_id).descendants.pluck(:id)) }
end
class Category < ActiveRecord::Base
has_many :products
acts_as_nested_set
end
ActiveAdmin.register Product do
filter :category
end
Categories are hierarchical.
When I enter category in filter I should see all products of that category and it's descendant categories (in_category scope in Product model).
Now ActiveAdmin uses ransack instead of metasearch and oldest approaches does not work.
Upvotes: 1
Views: 2412
Reputation: 2304
Here is article how to create a custom column on index page in ActiveAdmin and add custom filter based on Ransack:
http://codeonhill.com/activeadmin-custom-column-and-its-filter/
Upvotes: 0
Reputation: 11
Solution for my example.
In Product model:
ransacker :containing_category,
:formatter => ->(v) { ids = Category.find(v).self_and_descendants.pluck(:id);
ids.present? ? ids : nil } do |product|
product.table[:category_id]
end
Filter:
filter :containing_category_in,
as: :select,
label: 'Category',
collection: Category.all
Upvotes: 1