Forum: Ruby on Rails Ensuring both objects in a one-to-many association are not saved without the presence of the other

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.
C608d449f87ba87dd4a3f653afb304c1?d=identicon&s=25 Evan (Guest)
on 2008-10-20 05:36
(Received via mailing list)
Hello.

I have an object which is related to a second object through has_many.
The second object (obviously) is related to the first through
belongs_to. I want to ensure that neither object is saved to the
database without the presence of the other. How can I do this?

Thanks.

Evan
C5c0e0499446b84fd3bcc61cf7862539?d=identicon&s=25 Thani Ararsu (thaniyarasu)
on 2008-10-20 06:45
Evan wrote:
> Hello.
>
> I have an object which is related to a second object through has_many.
> The second object (obviously) is related to the first through
> belongs_to. I want to ensure that neither object is saved to the
> database without the presence of the other. How can I do this?
>
> Thanks.
>
> Evan


Use transaction
C608d449f87ba87dd4a3f653afb304c1?d=identicon&s=25 Evan (Guest)
on 2008-10-20 07:01
(Received via mailing list)
Even with transactions can I save the object containing the foreign
key without saving the primary object first? In other words, can I
save the object that requires the foreign key to be present if I don't
have the foreign key because the primary object has not yet been
saved, thus generating an id for it?
C608d449f87ba87dd4a3f653afb304c1?d=identicon&s=25 Evan (Guest)
on 2008-10-20 07:03
(Received via mailing list)
Oh wait. I think I just got it. Start a transaction, save the primary
object thus getting the id, save the secondary object, end
transaction. Right?
C608d449f87ba87dd4a3f653afb304c1?d=identicon&s=25 Evan (Guest)
on 2008-10-20 07:45
(Received via mailing list)
I guess the question I was really getting at is how can I validate the
presence and association of both objects before they are saved? I feel
more confident when there is code in the model itself to ensure the
integrity of the data rather than depending on each programmer to
place every save in a transaction block.
29ebf90af6107d2eb39b587c7972639c?d=identicon&s=25 Mukund (Guest)
on 2008-10-20 11:45
(Received via mailing list)
This topic is locked and can not be replied to.