nil:NilClass 的 NoMethodError 未定义方法“[]=”

NoMethodError undefined method `[]=' for nil:NilClass

我用一种测试方法创建了多个 classes 来测试 ruby 对象是否正确序列化。

返回的错误:

undefined method `[]=' for nil:NilClass
    from /Users/horse/workspace/queryapi/app/models/query_model.rb:193:in `serialize'

我 运行 通过 rails 控制台通过初始化 QueryModelTester 然后对该对象调用 test_query() 方法来 test_query 方法。

我的代码:

class QueryModelTester
  def test_query
    must = Must.new
    range_criteria = RangeCriteria.new 
    range_criteria.gte = 20140712
    range_criteria.lte = 1405134711

    range = RangeBuilder.new
    range.search_field = "created_time"
    range.range_criteria = range_criteria

    must.range = range
    bool = Bool.new
    bool.must = must

    main_query = bool.serialize
    puts main_query
  end
end

以下是模型 class,上面 class 正在测试:

class RangeCriteria    
  @query_hash = Hash.new
  attr_accessor :gte, :lte

  def serialize
    if(@gte.present?)
      @query_hash[:gte] = @gte
    end

    if(@lte.present?)
      @query_hash[:lte] = @lte
    end

    if(@gte.present? || @lte.present?) 
      return @query_hash
    end
  end
end


class RangeBuilder
  @query_hash = Hash.new
  attr_accessor :search_field, :range_criteria

  def serialize
    if(@search_field.present?)
      @query_hash[@search_field] = @range_criteria.serialize
      return @query_hash[:range] = @query_hash
    end
  end    
end

class Bool
  @query_hash = {}
  attr_accessor :must

  def serialize
    if( @must.present? )
      @query_hash[:must] = @must.serialize
      return @query_hash[:bool] = @query_hash
    end
  end
end

问题出在您初始化 @query_hash 时。在你所有的 类 中,它们都在错误的范围内初始化。要修复它,您应该将 @query_hash = Hash.new 移动到 initialize 方法,例如:

class RangeCriteria
  def initialize
    @query_hash = Hash.new
  end
    # ...
end

class RangeBuilder
  def initialize
    @query_hash = Hash.new
  end
    # ...
end

class Bool
  def initialize
    @query_hash = Hash.new
  end
    # ...
end

希望对您有所帮助。

祝你好运!