nil.id problem: Wondering why the id 4 is getting saved in Table instead of actual id?


Today I figured out the problem which is troubling me from 3-4 months, I am referring here it as “nil.id problem” .
Actually the situation was: User belongs_to :network, and Network has_many :users (simple association)
so I wanted to save network id in users table as network_id an attribute. There were all the necessary validations in User model(like validate_presence_of :network_id etc..). But some times(once in thousands) it saves ‘4′ as a network_id, which was a big problem because there was no network with id ‘4′, so where this ‘4′ came from, any idea???

Answer: I faced this problem today again with some other model. And I started digging around this and finally got the root of this bug. Actually I was saving user object like:

Now, what if group.network return nil, will it throw an exception? No, In that case user.network_id will be 4, because then user.network_id is actually saving nil.id and nil.id is always ‘4′. And this was the root of that error. But nil.id is deprecated now.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Travel Mate: New Widget For Opera
Stuck with capistrano
If my code or post helps you then please recommend me at workingwithrails.com by clicking on button below:
Recommend Me

Reader Comments

As I understand it is better to write


user.network = group.network

and then you would not get user.network_id = 4

nil.to_i=0 and nil.to_s=”" since both the methods are defined for nil class

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.