Tobie Langel
2005-Dec-04  19:19 UTC
How to create multiple objects from the same model on one form
Dear All,
On p. 356 of Agile Web Development with Rails, there is a method 
describing how to edit multiple objects from the same model on one 
form:
Here''s the text:
<quote>
Forms Containing Collections
If you need to edit multiple objects from the same model on one form, 
add open and closed brackets to the name of the instance variable you 
pass to the form helpers. This tells Rails to include the object’s id 
as part of the field name. For example, the following template lets a 
user alter one or more image URLs associated with a list of products.
   <%= start_form_tag %>
       <% for @product in @products %>
           <%= text_field("product[]",
''image_url'')%><br />
       <% end %>
       <%= submit_tag %>
   <%= end_form_tag %>
When the form is submitted to the controller, params[:product] will be 
a hash of hashes, where each key is the id of a model object and the 
corresponding value are the values from the form for that object. In 
the controller, this could be used to update all product rows with 
something like
Product.update(params[:product].keys, params[:product].values)
</quote>
I would like to be able to do exactly the same thing, but on create.
Any idea how I could work this out?
I know (still from Agile Web Dev p. 212) that "you can pass create( ) 
an array of attribute hashes; it’ll create multiple rows in the 
database and return an array of the corresponding model objects."
But how would I go about setting up my view to pass this information 
over?
I''ve looked all over the rails Wiki, googled for it, chatted on irc... 
without much success...
Anyone has an idea about how to do that properly?
Thanks and best regards,
Tobie
Justin
2006-May-23  05:50 UTC
[Rails] Re: How to create multiple objects from the same model on one form
Hello all, I realize that this message is old and may have been answered elsewhere, but if the answer exists I cannot find it. I had the same issue and found a solution so I thought it only fair to post a response. If you want to use the mentioned technique on create instead of update you must ensure that each model object, in this case the ''product'' has an id set and that each product has a unique id. Then do something like this in the controller after the form has been posted: for key in products.keys new_product = Product.new(:value => products[key]) end Hope this helps, Justin