在Rails 3中调用id为nil

时间:2011-09-26 12:03:38

标签: ruby-on-rails ruby ruby-on-rails-3

在开发模式中:

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

为什么?

4 个答案:

答案 0 :(得分:11)

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

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

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

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

答案 1 :(得分:2)

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

 config.whiny_nils = true

当您尝试在nil上调用方法时,会记录错误。 nil的ID是4,因为it is an object which happens to have an id of 4

答案 2 :(得分:2)

方法代码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 <tt>config.whiny_nils</tt> 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

答案 3 :(得分:1)

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

  

“Whiny nils”是将警告放入日志的Rails术语   每当一个方法被调用nil值时,(希望)有用   有关您可能尝试过哪种对象的信息   使用