In a rails app with associations (Such as Post belongs_to user), a common exception is this:
NoMethodError: undefined method `user' for nil:NilClass
Ubiquitously, this causes beginners to believe that user is nil. Why don't we have more intuitive errors, such as the following?
NoMethodError: `@post' is a nil:NilClass and doesn't have the method `user'
EDIT: Why is this being downvoted? The question is legitimate. I'd like to know if there is a technical reason preventing this.
First of all, I disagree with the original assertion. The message clearly says that user is an undefined method, not a variable or a value. I'm not sure how someone could think user is a variable based on this message.
However the answer to your question is that by the time the "user" method is called, the target object has already been loaded from whatever variable referenced it. The call logic for invoking "user" doesn't know anything about where that object came from. It could have been a local variable, an instance variable, a constant...there's no way to tell. Also, the Rails "whiny nil" logic happens in a method_missing implementation, far, far away from the original access of the object; the context of the original variable lookup is not even in scope anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With