Forum: Ruby on Rails has_many - when are child objects created?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
786aca6b4728622a57a2c34fb1c9f0cd?d=identicon&s=25 Rich Brant (Guest)
on 2006-01-05 21:00
(Received via mailing list)
I has several model objects that flow down like a tree:

Class1 has_many Class2
Class2 has_many Class3

and so on.

when are the child records actually created?

If I do:

c1 = Class1.find(:all)

are the child objects (C2s below) created then or not until i do
something like:

c2s = c1.C2s while iterating through the c1s?


If the form, that's cool, no problem, but If I've got say 1000 recs in
each of the tables corresponding to the has many relationship, that
could be quite a problem, right? And I'm aware I can append columns to
an object to prevent it, but I may not want to do it that way.  When I
actually do something like c2 = c1.C2s, I will want of that attributes
of those child objects. So my question is is there a way to prevent
the relationship when you want to, even if it's defined in the class?

thanks!


rb
Eea7ad39737b0dbf3de38874e0a6c7d8?d=identicon&s=25 Justin Forder (Guest)
on 2006-01-07 22:34
(Received via mailing list)
Rich Brant wrote:

>
> an object to prevent it, but I may not want to do it that way.  When I
> actually do something like c2 = c1.C2s, I will want of that attributes
> of those child objects. So my question is is there a way to prevent
> the relationship when you want to, even if it's defined in the class?

By default, it's the latter behaviour - children are loaded 'lazily',
when referenced.

You can get eager loading of one level of children using the :include
option in your find, e.g.

posts = Post.find(:all, :include => [ :author, :comments ])

See the section on Eager Loading in
http://ar.rubyonrails.com/classes/ActiveRecord/Ass...

regards

   Justin
This topic is locked and can not be replied to.