I have the next controller action:
def index
query = params[:query].presence || "*"
args = {}
args[:name] = params[:name] if params[:name].present?
args[:category_name] = params[:category_name] if params[:category_name].present?
@items = Item.search query, where: args, aggs: { category_name: {} }
end
I need to filter by name and by category (done)
But, also i need filter by two differents categories, for example:
category: "School", items: Notebook, Pencil, Pen, Board, etc
category: "Fruit", items: Banana, Pear, Grape, Apple, etc
category: "Vegetable", items: Broccoli, Carrots, Corn, Potatoes, etc
Then, the user selects "School" AND "Fruit" and the result should be a list of:
Notebook, Pencil, Pen, Board, etc
Banana, Pear, Grape, Apple, etc
Currently I have several different filters, I just put the "category" to show the problem, and I manage to filter results by all filters but only once each.
How can I handle the filters to allow two selections of the same filter?
Thanks!
Versions:
Rails 6.0.1
Ruby 2.6.5
Searchkick 4.1.1
You should be able to do this by simply passing an array of values to args[:category_name]
.
You could set up your search form so that your params[:category_name]
returns an array of multiple selections and it should just work. Just to be safe, we can coerce the value into an array when necessary like so:
args[:category_name] = Array(params[:category_name]) if params[:category_name].present?