1

rails 7.0.4 activeadmin 2.12.13

I have an admin page for the model Product. A Product contains a field product_number.

I have the following code in admin/products.rb:

  filter :product_number_equals, as: :string, label: 'Product Number'

Currently the filter only works for a single product number, but I want to allow the user to enter comma-separated values and show all products that contain any of the given product numbers. I thought, naively, this would be a walk in the park. Boy, how wrong I was! I've spent a far more time than I should trying to make this work. I've tried overriding #scoped_collection and #apply_filtering to no avail. Tweaking ransack in the model class didn't help either. I'm sure I'm doing something wrong. It's driving me mad!

ragis
  • 93
  • 4
  • You would need to build a custom filter for that [See Here](https://stackoverflow.com/questions/7983654/how-to-add-custom-filter-to-active-admin) for ideas. – engineersmnky Mar 07 '23 at 17:15

1 Answers1

2

Found the solution finally. Thanks Slack Overflow for being a wonderful rubber duck.

# models/product.rb

class Product < ApplicationRecord
  scope :product_number_one_of, lambda { |product_numbers|
    product_numbers = product_numbers.split(',').map(&:strip) if product_numbers.is_a?(String)
    where(product_number: product_numbers)
  }

  def self.ransackable_scopes(*)
    [:product_number_one_of]
  end
end
# admin/products.rb

ActiveAdmin.register Product do
  # ...
  filter :product_number_one_of, as: :string, label: 'Product Number'
  # ...
end
ragis
  • 93
  • 4