_form rendering question for adding multiple child objects

Hi

I have been following a thread here…
http://www.ruby-forum.com/topic/new?forum_id=3 but it did raise some new
curiosities that I hope someone can help address here :slight_smile:

In particular it is with Duane’s super secret hack that works for
multiple child objects

There’s a super-secret and mostly undocumented way of doing this
that’s kind of handy, actually. It looks like this:

<% for @comment in @post.comments %>
<%= text_field ‘comment[]’, ‘author’ %>
<%= text_field ‘comment[]’, ‘body’ %>
<% end %>

The FormTagHelper will pick up the square brackets and realize you
want the index of the object in there, producing HTML like this:


The trouble is, while this would work for editing existing objects, is
there a similar workaround for instantiating multiple child objects?

Let’s say for instance I have a object Person which has_many
VehicleRegistrations, and I want to have a form that would enable me to
instantiate many VehicleRegistrations at once.

So supposing my form enables 2 vehicleregistrations to be entered
alongside with the fields for Person, do I use something like

<%= text_field ‘Person.VehicleRegistrations[]’, ‘licenseNumber’ %>
<%= text_field ‘Person.VehicleRegistrations[]’, ‘vehicleManufacturer’ %>
<%= text_field ‘Person.VehicleRegistrations[]’, ‘vehicleMake’ %>

<%= text_field ‘Person.VehicleRegistrations[]’, ‘licenseNumber’ %>
<%= text_field ‘Person.VehicleRegistrations[]’, ‘vehicleManufacturer’ %>
<%= text_field ‘Person.VehicleRegistrations[]’, ‘vehicleMake’ %>

And hope that formTagHelper will be smart to realise that Person has a
has_many relationship with VehicleRegistrations and munge in the field
values for the array of VehicleRegistration?

Thanks

In particular it is with Duane’s super secret hack that works for
multiple child objects

There’s a super-secret and mostly undocumented way of doing this
that’s kind of handy, actually. It looks like this:

It’s not really a super secret hack; it is mentioned in AWDWR. And it’s
mentioned in passing in the API docs here, just before the Methods
listing:
http://rails.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

I’m trying to do the same kind of thing, and in fact, I’ve also got a
thread started about this issue (although no one has replied yet).

As far as I can tell, doing it the way you suggest doesn’t work because
Rails doesn’t know the id’s yet for the new objects, and so can’t setup
the arrays in the template. I’ve tried assigned the objects to an array
in the controller, and then explicitly reference that array in the
template, but is says that is not an allowed name for an instance
variable.

I’ll be watching with interest for any suggestions on this problem.