Shaliko Usubov
Shaliko Usubov

Reputation: 477

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 nil, use object_id"

In production mode:

nil.id
=> 4

Why?

Upvotes: 5

Views: 2450

Answers (4)

Benoit Garret
Benoit Garret

Reputation: 13675

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.

Upvotes: 11

Alexander Sulim
Alexander Sulim

Reputation: 136

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

Upvotes: 2

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

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.

Upvotes: 1

Dan McClain
Dan McClain

Reputation: 11920

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

Upvotes: 2

Related Questions