0
votes

i'm trying to make an advanced search in my rails app but i'm having some problems with empty params

class Product< ActiveRecord::Base searchkick

when i fill the search and size fields everyting works, but if i leave size field blank nothing show up in the results...

probably i'm doing something stupid

i made it work with a bunch of IFs:

def index

if params[:search].present?
  if params[:size].present?
    @products = Product.search params[:search], where: {size: params[:size]}
  else
    @products = Product.search params[:search]
  end      
else
  if params[:size].present?
    @products = Product.search "*", where: {size: params[:size]}
  else
    @products = Product.search "*"
  end

end

but probably thats not the best approuch, having in mind that i will search in at least 5 other fields...

Search, Size, Brand, Color, Store.state, Price, Rating etc...

sorry for my english, i hope you guys understand my question and get able to help me..

2

2 Answers

0
votes

My be smth:

...
search_condition = params[:search] || '*'
where_conditions = params.slice(:size, :brand, :color, ...)

@products = if where_conditions.any?
  Product.search search_condition, where: where_conditions
else
  Product.search search_condition
end
0
votes

Found a solution where

Setting up Facets in Elasticsearch with Searchkick gem in Rails 4.1

 query = params[:query].presence || "*"
 conditions = {}
 conditions[:state] = params[:state] if params[:state].present?
 conditions[:city] = params[:city] if params[:city].present?

 movies = Movie.search query, where: conditions