检查param是否有值失败(NoMethodError(未定义的方法`[]'为nil:NilClass):)

时间:2012-09-01 09:25:12

标签: ruby-on-rails ruby-on-rails-3 params null param

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

if params ['/ people'] [:age_from] .present? &安培;&安培; PARAMS [ '/人'] [: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

1 个答案:

答案 0 :(得分:1)

这是因为params['/people']是nil,而nil []完全返回你得到的错误。

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

if params['/people'] && params['/people'][:gender].present && params['/people'][:gender] == "male"