Rails 为 nil:NilClass 抛出未定义的方法“[]”甚至认为一切正常

Rails throwing undefined method `[]' for nil:NilClass even thought everything is working

我在路线 'memorisation' 有一个视图,它有一个 CSV 文件类型的文件导入。当我 运行 导入时,所有更改似乎都适用于所有 139 条记录。但是,我仍然遇到错误。

NoMethodError in MemorisationController#import
undefined method `[]' for nil:NilClass

这是我的控制器方法:

  def import
    require 'csv'
    all_targets = MemoTarget.order(:id).includes(:memo_level).map do |t|
      {
      :id => t.id,
      :target => t.target_number,
      :level => t.memo_level.level_number
      }
    end
    CSV.foreach(params[:file].path, headers: true) do |row|
      the_target = MemoTest.create do |test|
        test.student_id = row["student_id"]
        test.teacher_id = session[:user_id]
        test.memo_target_id = all_targets.find {|t| t[:level] == row["memo_level"].to_i and t[:target] == row["memo_target"].to_i}[:id]
        test.result = true
      end
    end
    redirect_to '/memorisation', notice: 'Student memorisation current targets imported'
  end

test.memo_target_id = all_targets.find {|t| t[:level] == row["memo_level"].to_i and t[:target] == row["memo_target"].to_i}[:id] 行抛出错误。

在我的服务器日志中,所有预期的更改都在进行,如 SQL COMMITs 所示。提交后,控制器应重定向回 memorisation 页面。

   ...
   (0.7ms)  COMMIT
   (0.3ms)  BEGIN
  SQL (0.5ms)  INSERT INTO "memo_tests" ("student_id", "teacher_id", "memo_target_id", "result", "created_at", "updated_at") VALUES (, , , , , ) RETURNING "id"  [["student_id", 139], ["teacher_id", 1], ["memo_target_id", 30], ["result", "t"], ["created_at", "2015-09-13 08:08:05.205922"], ["updated_at", "2015-09-13 08:08:05.205922"]]
   (0.6ms)  COMMIT
Completed 500 Internal Server Error in 6145ms

NoMethodError (undefined method `[]' for nil:NilClass):
  app/controllers/memorisation_controller.rb:33:in `block (2 levels) in import'
  app/controllers/memorisation_controller.rb:30:in `block in import'
  app/controllers/memorisation_controller.rb:29:in `import'


  Rendered /Users/Javu/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (135.6ms)
  Rendered /Users/Javu/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (69.8ms)
  Rendered /Users/Javu/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (13.1ms)
  Rendered /Users/Javu/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (270.0ms)
Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0x007fd4d2cd4c28 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x007fd4d2cd4868 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x007fd4d2ccc2a8 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

我已经用byebug查看了导入或第139条记录是否有问题,但似乎一切正常。

我想知道导致此错误的原因以及如何纠正它。

row 在您的 CSV 文件中是 nil,这就是您收到此错误的原因,请尝试下面的代码,它会起作用。

def import
  require 'csv'
  all_targets = MemoTarget.order(:id).includes(:memo_level).map do |t|
    {
    :id => t.id,
    :target => t.target_number,
    :level => t.memo_level.level_number
    }
  end
  CSV.foreach(params[:file].path, headers: true) do |row|
    next if row.all?(&:blank?)
    the_target = MemoTest.create do |test|
      test.student_id = row["student_id"]
      test.teacher_id = session[:user_id]
      test.memo_target_id = all_targets.find {|t| t[:level] == row["memo_level"].to_i and t[:target] == row["memo_target"].to_i}[:id]
      test.result = true
    end
  end
  redirect_to '/memorisation', notice: 'Student memorisation current targets imported'
end