Ruby on Rails:nil的未定义方法`call’:NilClass

这是它登陆的路线。

@object = Object.find(params[:id]) respond_to do |format| if @object.update_attributes(:status=>Object::PUBLISHED, :published_at => Time.now) format.html { redirect_to :action => :publish_detail } format.xml { head :ok } format.json { head :ok } #else # flash[:error] = 'There was a problem updating your object.' # format.html { redirect_to :action => "publish_detail" } # format.xml { render :xml => @object.errors, :status => :unprocessable_entity } # format.json { render :json => @object.errors, :status => :unprocessable_entity } end end 

和堆栈跟踪

 /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/whiny_nil.rb:52:in `method_missing' /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.8/lib/action_controller/mime_responds.rb:175:in `respond' /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.8/lib/action_controller/mime_responds.rb:173:in `each' /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.8/lib/action_controller/mime_responds.rb:173:in `respond' /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.8/lib/action_controller/mime_responds.rb:107:in `respond_to' .../app/controllers/objects_controller.rb:252:in `publish' 

为什么我会在那里收到错误?

我补充道

 puts "||||||||||||||||||#{@object.name}" 

并且控制台显示该对象不是nil .. = \

日志显示:

 NoMethodError (undefined method `call' for nil:NilClass): app/controllers/objects_controller.rb:252:in `publish' Rendered rescues/_trace (26.1ms) Rendered rescues/_request_and_response (1.1ms) Rendering rescues/layout (internal_server_error) 

这意味着……呃……你试图在“零”对象上调用“调用”方法。

当你使用一个认为它应该是vaild的对象时,会发生这种情况,而不是nil。 例如,如果Object.find找不到对象并返回“nil”,则可能是这种情况。

@object将是“nil”,你不能把它当作Object类型对待它。

编辑:总是检查使用“无?” 在使用具有不确定性的物体之前。

事实certificate,这个错误发生了,因为(在rails 2.3.8中)我猜你不能用date_select设置日期时间。

所以我将f.date_select更改为f.datetime_select并重新保存日期,一切都很顺利。