1

Does pushing an entity to a it's parent collection causes the collection to be loaded?

e.g.:

Parent.childs << a_child

Is the parent.childs "array" now loaded with ALL the childs or just "a_child" ? i.e. will a SQL "select * from childs where parent_id = ?" statement will be executed before adding to the collection?

EDIT:

http://apidock.com/rails/v3.2.3/ActiveRecord/Associations/CollectionAssociation/concat_records seems to call "add_target" BEFORE calling "insert_record" which adds the entity to the @target array...

tereško
  • 58,060
  • 25
  • 98
  • 150
d0bz
  • 165
  • 9

1 Answers1

2

No (thank god)! Parent.childs is a Proxy and '<<' will just trigger the creation/update of a_child

More info on How do rails association methods work?

Also in the rails comments of associations/collection_associations.rb

You need to be careful with assumptions regarding the target: The proxy does not fetch records from the database until it needs them, but new ones created with +build+ are added to the target. So, the target may be non-empty and still lack children waiting to be read from the database. If you look directly to the database you cannot assume that's the entire collection because new records may have been added to the target, etc.

A quick check on my console confirmed there the children aren't loaded.

parent.children << child; nil

=> only parent and child where loaded....

Community
  • 1
  • 1
charlysisto
  • 3,700
  • 17
  • 30
  • Hum maybe my question was not clear because i already know that. Please refer to my latest edit. TYVM. – d0bz Jan 16 '13 at 15:47