Creating multiple objects with one form


#1

How do you create multiple objects with one form? For example:

<% form_for :user, :url => users_path, :html => { :method => :post }
do |f| %>

Name: <%= f.text_field :name %> Number: <%= f.text_field :number %> Name: <%= f.text_field :name %> Number: <%= f.text_field :number %>

<%= submit_tag "Create Users" %>


#2

Surely this must be common …


#3

For multiple objects of the same type just add a :index argument to
each of the form fields. Here is an example:

<%= f.select :rating, @ratings, {}, {:index => post.id} %>

For existing objects you can use the objects id for an index, for new
objects just use some kind of counter. When you submit the form the
index objects will be rolled up into a hash that you can then step
through and process.

Aaron


#4

Thanks for the reply. I don’t get what you mean by using some kind of
counter. I’ve taken a look at this post but don’t think it suits my
needs:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/10ab20cf27de5725/1d739f6058c9f4ba?lnk=gst&q=multiple+object&rnum=6#1d739f6058c9f4ba

I’ve got all the rails books and cannot find some documentation on how
to do something like this.


#5

Thanks for the reply. How would one implement this if the number of
objects is unknown until the post?


#6

I plan on using rjs insert_html for each additional object beyond one
that the user wants to create. The reason why I am doing it this way
is because the objects that are created, each will have the same
foreign key (mapped to a different model). If their all going to have
the same foreign keys, I think it makes sense to create them all on
the same form/view.


#7

I’m just going to create 5 unique indexed objects for the ‘new’
action. Thanks for your help Aaron!


#8

The :index value needs to be unique for each object. If he objects
already exist the id works great, otherwise you need to create a
unique key for each object. The code below uses the counter loop
variable for the :index value.

wrap everything in a form_for

<%= form_for … %>

loop to create multiple objects

<% 3.times do |counter| %>
# setup fields for each object
<% fields_for posts, post do |post_fields| %>
# use the counter variable for the :index key
<%= post_fields.select :rating, @ratings, {}, {:index =>
counter} %>
<%= post_fields.text_field :name, :index => counter %>
<% end %>
<% end %>
<% end %>

Aaron


#9

I found some of the tutorials at railsforum.com useful for figuring
out how to do this. Specifically:

http://www.railsforum.com/viewtopic.php?id=719
http://www.railsforum.com/viewtopic.php?id=1063
http://www.railsforum.com/viewtopic.php?id=1065

Michael
www.mslater.com