Called id for nil in Rails 3
In development mode:
nil.id
=> "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of开发者_StackOverflow中文版 nil, use object_id"
In production mode:
nil.id
=> 4
Why?
Look for the line that says the following in your environments configs:
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true # or false in production.rb
This is to prevent you from calling methods on nil
while in development mode. I guess they disabled it for performance reasons in production.
And nil
is a singleton object in ruby, that's why its id
will be 4 no matter what.
Your development.rb evironment has the following line:
config.whiny_nils = true
Which will log an error when you try to call a method on nil
. nil
's id is 4 because it is an object which happens to have an id of 4
Code of method NilClass#id
has good explanation:
# 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
Whiny nils are only reported during development mode (look into your config files).
"Whiny nils" is the Rails term for putting warnings into the log whenever a method is invoked on a nil value, with (hopefully) helpful information about which sort of object you might have been trying to use.
精彩评论