Forum: Ruby on Rails How to save parent and child objects in a single action?

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.
Szymon N. (Guest)
on 2006-03-15 01:16
Hi!

I'm struggling with it for a week. I posted a few similar posts that
cleared up few things (thanks Mark!), but i still don't know how to do
it properly.

What i'm trying to do is to create parent object and its many children
(images - i tried using file_column, but it's a topic for another
post)using data from a single form.

I've got a working version of it, but i can't validate anything because
the code doesn't work properly, when data doesn't pass validation.

To simplify things: how to write code for a controller that will save
parent object, its child object and will work with validation? I mean if
any object fails validation, the data for all objects will be available
for editing (correcting) and all objects will be saved only if they all
pass validation.

Thanks in advance for any help.
Mark Reginald J. (Guest)
on 2006-03-15 16:00
(Received via mailing list)
szymek wrote:

> To simplify things: how to write code for a controller that will save
> parent object, its child object and will work with validation? I mean if
> any object fails validation, the data for all objects will be available
> for editing (correcting) and all objects will be saved only if they all
> pass validation.

valid_images = @images.inject(true) { |v, i| v = i.valid? && v }
if @parent.valid? && valid_images
   @parent.images << @images
   @parent.save(false)
   redirect_to :action => 'show_parent'
end

--
We develop, watch us RoR, in numbers too big to ignore.
Szymon N. (Guest)
on 2006-03-16 16:04
Thanks once again!
Dave Myron (Guest)
on 2006-03-17 21:55
(Received via mailing list)
I haven't used it so I might be wrong, but maybe look into model
transactions?

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