2012-09-01 75 views
0

使用下面的搜索方法我無法檢查參數是否存在。 它總是拋出一個NoMethodError(未定義方法`[]'nil:NilClass):檢查參數是否有值失敗(NoMethodError(未定義方法'[]'爲零:NilClass):)

if params ['/ people'] [:age_from] .present? & & params ['/ 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 
+0

你爲什麼要做'params ['/ people']'?這對我來說看起來不像是有效的語法。 –

回答

1

這是因爲params['/people']是零,而零你得到你也應該檢查在哈希第一部分的存在,如[]返回完全錯誤

if params['/people'] && params['/people'][:gender].present && params['/people'][:gender] == "male" 
相關問題