在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.
仅在开发模式期间报告Whiny nils(查看配置文件)。
“Whiny nils”是Rails术语,用于在nil值上调用方法时将警告放入日志中,并且(希望)有关您可能尝试使用哪种对象的有用信息。