在Rails 3中调用id为nil

在开发模式中:

nil.id => "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id" 

在生产模式:

 nil.id => 4 

为什么?

在您的环境配置中查找说明以下内容的行:

 # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # or false in production.rb 

这是为了防止您在开发模式下调用nil方法。 我猜他们在生产中出于性能原因禁用了它。

nil是ruby中的单例对象,这就是为什么它的id无论如何都是4。

您的development.rb环境有以下几行:

  config.whiny_nils = true 

当您尝试在nil上调用方法时,将记录错误。 nil的id是4,因为它是一个碰巧id为4的对象

方法代码NilClass#id有很好的解释:

 # NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental # method of Active Record models NilClass#id is redefined as well to raise a RuntimeError # and warn the user. She probably wanted a model database identifier and the 4 # returned by the original method could result in obscure bugs. # # The flag config.whiny_nils determines whether this feature is enabled. # By default it is on in development and test modes, and it is off in production # mode. 

https://github.com/rails/rails/blob/0c76eb1106dc82bb0e3cc50498383d6f992da4fb/activesupport/lib/active_support/whiny_nil.rb#L19

仅在开发模式期间报告Whiny nils(查看配置文件)。

“Whiny nils”是Rails术语,用于在nil值上调用方法时将警告放入日志中,并且(希望)有关您可能尝试使用哪种对象的有用信息。