Ruby变量似乎是零,但不是零

时间:2016-03-08 10:46:43

标签: ruby-on-rails ruby

我在标记的行处收到错误LOAD DATA REPLACE INTO TABLE tableHeader WHEN RECTYPE = 'HEADER|' FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS ( RECTYPE FILLER POSITION(1:7), FILL1 FILLER, FILL2 FILLER, HEADER_DETAIL ) INTO TABLE tableDetail WHEN RECTYPE = 'DETAIL|' FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS ( RECTYPE FILLER POSITION(1:7), DATA1, DATA2, DATA3 ) INTO TABLE tableFooter WHEN RECTYPE = 'FOOTER|' FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS ( RECTYPE FILLER POSITION(1:7), FOOTER_DETAIL ) 。记录器显示undefined method '[]' for nil:NilClass不是零。我似乎并没有在该行的其他任何地方调用此方法。我在这里缺少什么?

hash

这是记录器的输出:

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

1 个答案:

答案 0 :(得分:5)

您覆盖initialize,因此您的ActiveRecord对象未正确初始化。引发错误是因为self.name在内部尝试更新实例的attributes哈希并失败。

当您覆盖initialize方法时,首先调用super以运行默认的initialize方法是有意义的:

def initialize(hash)
  super(hash.slice(:name, :type, :default_value))
  self.original_name = hash[original_name] || name
end