views:

539

answers:

1

Trying to use the nested model form in the new rails release candidate. I have this, but it only renders form fields for each existing associated photo object.

(Given a form builder f that was created for my parent model object)

%h3 Photos

- f.fields_for :photos do |photo_form|
  %p
    = photo_form.label :caption
    = photo_form.text_field :caption

  %p
    = photo_form.label :image_file
    = photo_form.file_field :image_file

How can I use this nested forms feature to create a section of the form for a new photo object as well as editing the existing photos?

+1  A: 

The associated objects just need to exist in memory to be rendered in the form, they don't need to be saved. So you can build them before you render the form!

For example, in your controller, you can do:

def new
  @object = MyObject.new
  3.times { @object.build_associated_object }
end

Now when your form renders, it has 3 objects to display forms for! That's the easiest way. Of course, you can also add items dynamically with Javascript.

Ian Terrell