0

使用以下搜索方法我无法检查参数是否存在。它总是抛出 NoMethodError(nil:NilClass 的未定义方法 `[]'):

if params['/people'][:age_from].present? && 参数['/people'][:age_to].present? 如果声明和性别声明似乎完全失败并且不知道为什么:(

   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

非常混乱:但这似乎有效

  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
4

1 回答 1

1

那是因为params['/people']是 nil,并且 nil[] 准确地返回您得到的错误。

您还应该检查哈希中第一部分是否存在,如下所示:

if params['/people'] && params['/people'][:gender].present && params['/people'][:gender] == "male"
于 2012-09-01T09:28:43.487 回答