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

Published on Author Akhil Bansal2 Comments

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:

user=User.new(params[:user])
user.network_id = group.network.id
user.save

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.

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

  1. As I understand it is better to write


    user.network = group.network

    and then you would not get user.network_id = 4

Leave a Reply

Your email address will not be published. Required fields are marked *