RoR崩溃保存“你有一个零对象,你没想到它”

时间:2011-01-06 07:06:45

标签: ruby-on-rails

我有一个我正在保存的RoR对象图。用户有一个部分列表。当请求进入时,我删除所有当前用户部分,并重新填充新部分。

def set_current
  @courses = params[:courses]
  user = current_user
  user.points = params[:points].nil? ? user.points : params[:points].to_i
  UserSection.delete(user.user_sections)
  @courses.each do |c|
    new_section = UserSection.new()
    new_section.user = user

    new_section.save
  end
  user.save

  head :ok
end

当我保存时,我明白了:

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.new_record?):
  app/controllers/schedule_controller.rb:32:in `set_current'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/1.8/webrick/server.rb:82:in `start'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.6/bin/rdebug-ide:82
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.6/bin/rdebug-ide:19:in `load'
  /Applications/NetBeans/NetBeans 6.9.1.app/Contents/Resources/NetBeans/ruby/jruby-1.5.1/bin/rdebug-ide:19

关于实际发生的事情的想法?保存成功 - 进入数据库和所有内容。

编辑:异常(schedule_controller.rb:32)是对user.save的调用

1 个答案:

答案 0 :(得分:0)

尝试用第一行替换(如果那是您的错误)

UserSection.delete(user.user_sections) if user.user_sections

但是像Zabba所说,代码清单会有所帮助。