activerecord · Rails

ActiveRecord : an interesting observation

While working with ActiveRecord I observed something interesting, worth sharing.

Say we have the relation:

author has_many books

Now I create a new author say ‘a’ and a new book say ‘b’

a = Author.new
b = Book.new

Now, If I have a piece of code where I push ‘b’ into ‘a’ without saving ‘a’ first, what should happen ?

Like I do it like this:

a.books << b

see that neither ‘a’ nor ‘b’ has been saved, so what should happen? Should it give an error quoting nil id in author table or something else ?

Well things turned out to be different rather, when we push ‘b’ into ‘a’ without saving ‘a’ first, it gets pushed !

Yes, you heard it, it gets pushed.

Now everybody will wonder that how is it possible, without any id in scenario till now how the actual relationship can be handled internally ? without any id or book_id how can two records inference them ?

Well I suppose (yeah it’s completely an assumption, I haven’t read ActiveRecord source yet !) that ActiveRecord pushes the child into an array maintained by the parent and as soon as we save the parent the child gets saved and pushed automatically.

that means, when I do :

a.save

b gets saved and pushed into a.books automatically.

Waiting for comments to clear the air !

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s