0

Using below search method Im unable to check if the params exists. It always throws an NoMethodError (undefined method `[]' for nil:NilClass):

The if params['/people'][:age_from].present? && params['/people'][:age_to].present? if statement and the one for gender seems to totally fail and have no idea why :(

   def self.search(params)

    puts params

    tire.search(load: true, page: params[:page], per_page: 20) do
      query do
        boolean do
          should { range :age, {gte: params['/people'][:age_from], lte: params['/people'][:age_to]} } if params['/people'][:age_from].present? && params['/people'][:age_to].present? 
          should { string 'gender:male' } if params['/people'][:gender].present && params['/people'][:gender] == "male" 
        end
      end
      to_curl
    end
  end

VERY messy: but this seems to work

  def self.search(params)
    if params['people']
      tire.search(load: true, page: params[:page], per_page: 20) do
        query do
          boolean do
            should { range :age, {gte: params['people'][:age_from], lte: params['people'][:age_to]} }
            should { string 'gender:male' } if params['people'][:gender] == "male"
            should { string 'gender:female' } if params['people'][:gender] == "female"
          end
        end
        to_curl
      end
    else
      if Rails.env == "development"
        @profiles = Profile.where('status IS NOT NULL').page(params[:page]).order("id").per_page(50)
      else
        @profiles = Profile.where("user_id != ?", current_user.id).where('status IS NOT NULL').order("id").page(params[:page]).per_page(40)
      end
    end

  end
Rubytastic
  • 15,001
  • 18
  • 87
  • 175

1 Answers1

1

That is because params['/people'] is nil, and nil[] returns exactly the error you are getting.

You should also check for the existence of the first part in the hash as in:

if params['/people'] && params['/people'][:gender].present && params['/people'][:gender] == "male"
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64