Two unsaved related objects


#1

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


#2

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


#3

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