【问题标题】:Undefined method '[]' for nil:NilClass when trying to write to db in active record [closed]尝试写入活动记录中的数据库时,nil:NilClass 的未定义方法“[]”[关闭]
【发布时间】:2015-12-15 15:11:47
【问题描述】:

来自 rails 中的活动记录方法(流线型仅用于说明流程):

class Model
  include Mongoid:Document
  include Mongoid:Timestamps

  belongs_to :record
  belongs_to :structure
  has_one :sim_engine, dependent: :destroy

  def init                        #Line 22
    if new_record?
      self.structure = record.structure
      self.sim_engine = SimEngine.create(function1,other_inputs...)
    end
  end

  def function1
    input_1 = ...
    input_2 = ...
    function1_hash = [ ]
    ...
    m = function2(input_1,input_2)
    function1_hash += m

  rescue Exception => e
    throw "Error in record #{record.id}: #{e.message}"     #Line 683
  end

  def function2(input_1,input_2)
    input_1.each do |value|
    function2_hash << value
  end

  temp = input_2.anotherClassFunctionCall()
  function2_hash << temp
end

当我跑步时:

Model.create!(record: 314675)

我得到以下错误跟踪:

ArgumentError: uncaught throw "Error in record 314675: undefined method '[]' for nil:NilClass'
from org/jruby/RubyKernel.java:1311: in 'throw'
from /srv/app/models/model.rb:683: in 'function1'    # See above sample code
from /srv/app/models/model.rb:22: in 'init'          # See above sample code
# The line numbers are commented in the above sample code

我试图弄清楚为什么会抛出错误异常,这是我的假设:

  1. 我尝试写入数据库 (mongodb) 的记录尚未定义。
  2. function1 方法中存在需要解决的错误。
  3. function2function1 继承的方法中存在错误。

【问题讨论】:

  • 你能发布一些堆栈跟踪吗?
  • 我们能看到真实的代码吗?你甚至没有在任何地方调用 init 方法。
  • 错误消息应该给你一个失败的行号。你看了吗?您尚未指出涉及到您的代码的哪一部分。
  • 实际上有几处错误。我的猜测是,该特定错误来自您在 Model 类中的最后一行。 function2_hash 被视为数组,但未在该范围内定义(仅在 function2 范围内定义)。在未定义的数组上使用&lt;&lt; 运算符时,会出现错误。
  • @richessler 我添加了跟踪。

标签: ruby-on-rails ruby mongodb


【解决方案1】:

我找到了原因

ArgumentError: uncaught throw "记录 314675 中的错误:nil:NilClass' 的未定义方法 '[]'

主要来自 def init 方法所需的一组不完整的输入变量。因为这是 function1 方法抛出的 ArgumentError,所以我只投入调试 function1。原始模型有 7 个输入变量,包括 function1。我意识到有几个输入变量与数据类型不匹配,例如,模型接受整数,而输入变量是字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多