How to save parent and child objects in a single action?

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.

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.

Thanks once again!

I haven’t used it so I might be wrong, but maybe look into model
transactions?

Dave