Search code examples
ruby-on-railsrubysearchkick

Searchkick where hash optional params


How to write this code with Ruby and Searchkick gem.

https://github.com/ankane/searchkick#queries

# Works
@espacos = User.search where: {
  gender: params[:gender], # options: :male and :female
  other_param: param,
  other_param: param
}

# How do search all if the parameter is not informed?
@espacos = User.search where: {
  if not nil params[:gender]
    gender: params[:gender],
  end
  other_param: param,
  other_param: param
}

Solution

  • options = {
      other_param: other_param
      yet_another: yet_another
    }
    
    options[:gender] = params[:gender] if params[:gender].present?
    

    Editing to satisfy request below

    [:gender, :sex, :colour].each do |s|
      options[:s] = params[:s] if params[:s].present?
    end