Forum: Ruby on Rails Two unsaved related objects

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.
John S. (Guest)
on 2006-03-15 00:17
(Received via mailing list)
Given the two tables Parent, Child where Parent has_many children:
If I don't save parent first then it seems that child.parent will not
be assigned automatically if I call parent.children << child . Must
the parent record be saved before I call parent.children << child ?

If I must save Parent first then can someone explain to me how I can
call parent.valid? before it is saved and have the children validated
too?

Any workaround I see requires a lot of coercing of these
relationships together over and over again.

-John

--
John S.
Computing Staff - Webmaster
Kavli Institute for Theoretical Physics
University of California, Santa Barbara
removed_email_address@domain.invalid
(805) 893-6307
Norman T. (Guest)
on 2006-03-15 11:46
(Received via mailing list)
Am Dienstag, den 14.03.2006, 14:16 -0800 schrieb John S.:
> Given the two tables Parent, Child where Parent has_many children:
> If I don't save parent first then it seems that child.parent will not
> be assigned automatically if I call parent.children << child . Must
> the parent record be saved before I call parent.children << child ?

As Child belongs_to Parent, the foreign key is stored in the children
table. If Parent is a new record and has no id, the children can't save
it as foreign key.

> If I must save Parent first then can someone explain to me how I can
> call parent.valid? before it is saved and have the children validated
> too?

if !parent.valid? || children.all? { |c| c.valid? }
  # some records are not valid
else
  parent.save
  parent.children << *children
end

So you never get a saved parent unless all children are valid, too.

--
Norman T.

http://blog.inlet-media.de
John S. (Guest)
on 2006-03-15 18:44
(Received via mailing list)
Using that form of validation means I cannot validate whether a child
has a parent or not. Isn't that a problem?

-John

--
John S.
Computing Staff - Webmaster
Kavli Institute for Theoretical Physics
University of California, Santa Barbara
removed_email_address@domain.invalid
(805) 893-6307
This topic is locked and can not be replied to.