[英]Ruby variable seems to be nil but is not nil
I get the error undefined method '[]' for nil:NilClass
at the marked line. 我在标记的行undefined method '[]' for nil:NilClass
的错误undefined method '[]' for nil:NilClass
。 The logger shows that hash
in not nil. 记录器显示该hash
不为nil。 It seems I don't call this method on anyhing else in that line. 似乎我在那一行的其他任何地方都没有调用此方法。 What am I missing here? 我在这里想念什么?
def initialize(hash)
Rails.logger.debug "Attr init hash: #{hash.inspect}, nil?: #{hash.nil?}"
self.name = hash[:name] #error here
self.type = hash[:type]
self.default_value = hash[:default_value]
self.original_name = if hash[:original_name]
hash[:original_name]
else
name
end
end
This is the output of the logger: 这是记录器的输出:
Attr init asdasd: {:name=>"join_id.alma", :type=>"", :default_value=>"", :original_name=>nil}, nil?: false
You overrode initialize
and therefore your ActiveRecord
object wasn't initialized correctly. 您覆盖了initialize
,因此您的ActiveRecord
对象未正确初始化。 The error is raised because self.name
internally tried to update the instance's attributes
hash and fails. 由于self.name
内部尝试更新实例的attributes
哈希而失败,因此引发了错误。
When you override the initialize
method it makes sense to call super
to run the default initialize
method first: 当您覆盖initialize
方法时,首先调用super
来运行默认的initialize
方法是有意义的:
def initialize(hash)
super(hash.slice(:name, :type, :default_value))
self.original_name = hash[original_name] || name
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.