[英]NoMethodError undefined method `[]=' for nil:NilClass
I created multiple classes with one test method to test wither the ruby objects get serialized correctly. 我用一种测试方法创建了多个类,以测试ruby对象正确地序列化。
The error returned: 错误返回:
undefined method `[]=' for nil:NilClass
from /Users/horse/workspace/queryapi/app/models/query_model.rb:193:in `serialize'
I run the below test_query method through the rails console by initializing QueryModelTester and then invoking test_query() method on that object. 我通过初始化QueryModelTester然后在该对象上调用test_query()方法,通过rails控制台运行以下test_query方法。
My code: 我的代码:
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
Here are the model classes the above class is testing: 这是上面的类正在测试的模型类:
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
The problem is when you initialize your @query_hash
. 问题是当您初始化@query_hash
。 In all your classes they are initialized in wrong scope. 在您所有的类中,它们都在错误的范围内初始化。 To fix it, you should move @query_hash = Hash.new
to initialize
method, like: 要修复它,您应该移动@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
Hope that helps. 希望能有所帮助。
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.