Saving multiple records from a single form

Usually a form maps to a AR instance (and hence a database row).

Consider the simple example of a Person model in which there is just one attribute “name”. [This is just an example to illustrate the problem]

Now I need a single form that allows multiple people to be added, basically multiple text fields (for “name” attribute) each resulting in a new ActiveRecord object for each person, but a single action and single submit button.

Another example would be multiple image upload from a single form [Flickr]

The way I am thinking of doing this is by having a model “People” that encapsulates many Person objects, on submit the controller method of Person shall iterate over its params and create as many Person objects as required. The People class though a model does not have a database table of its own.

My question : Is there a better way/pattern of doing this?

Thanks

Hi Nasir,

You're making it too hard for yourself. Just do the iteration in the controller, or make a method like "create_multiple" in your person model.

Cheers Starr

Hi Nasir,

Here is an example to accomplish what you are trying to do. The 'show' method starts things rolling. The 'people' table has only 'id' and 'name' columns.

The Model (person.rb): class Person < ActiveRecord::Base end

The Controller (person_controller.rb): class PersonController < ApplicationController

  def show   end

  def nbrOfNewPeople     3   end

  def add_person     nbrOfNewPeople.times do | index |       person = Person.new       personParams = params[('person' + index.to_s).intern]       person.update_attributes(personParams) unless personParams[:name].empty?     end   end

end

The View (show.rhtml) <%= form_tag :action=> 'add_person' %> <% controller.nbrOfNewPeople.times do | i | %> <label for='<%='person' + i.to_s%>'>Name:</label> <%= text_field 'person' + i.to_s, 'name' %> </br> <% end %> <%= submit_tag "Add People" %> <%= end_form_tag %>

Paul

Starr, Paul

Thanks a lot for your responses, I was making it too complex :frowning:

Just a minor refinement to Paul’s example - In the form, continue to let the text_field be associated with model person and let the field be named anything, in this case a number … <%= text_field ‘person’ , i.to_s %> …

In the controller extract the params in a hash

my_params = params[:person] my_params.each do |p| param_hash = {:name => p[1]} @person = Person.new(param_hash) … @person.save end

This allows me to have the controller not know the number of people that are sent from the form, so form can have a javascript which adds new text_fields to the form dynamically. [like gmail] Thanks