Forum: Ruby on Rails ActiveRecord: adding children to a has_many parent

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.
578f6d71f9a338772994b622dd51d86d?d=identicon&s=25 bataras (Guest)
on 2006-12-27 04:19
(Received via mailing list)
given parent.list is a has_many of Child, I've found that if I do this:

    child = Child.new(...)
    parent.list << child

rails will select * all of parent.list before doing the insert of the
new child (if parent.list isn't already loaded). This is -bad- because
my parent.list is huge.

So instead, I do this:

    child = Child.new(...)
    child.parent = parent
    child.save!

This ensures a single insert and also throws an exception if any DB
constraints are violated, thus ensuring any encompassing transactions
and/or top level logging is handled.

is this generally the right thing to do with rails? I'm a noob coming
from enterprise development in other languages.

Or is there some other magic way to add to parent.list with the above
kind behavior?
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2006-12-27 05:17
(Received via mailing list)
bataras wrote:
> So instead, I do this:
>
>    child = Child.new(...)
>    child.parent = parent
>    child.save!

The most terse way would be

   parent.list.create(...)

If you want to defer saving you can instead use the "build" method.

--
We develop, watch us RoR, in numbers too big to ignore.
578f6d71f9a338772994b622dd51d86d?d=identicon&s=25 bataras (Guest)
on 2006-12-27 07:39
(Received via mailing list)
Cool. Thanks. I'll use that. In one case though, I have to create a new
child that "belongs_to" 2 different kinds of parents. So for that, I'll
have to use the build method to make it happen in a single insert.
This topic is locked and can not be replied to.