Create multiple records simultaneously on one form

99 views Asked by At

After trying to accomplish the deceptively tricky task of building a form that enables the creation of multiple users at once, I wanted to pay it forward by sharing how I did it. Somewhat to my surprise, I was unable to find any SO answers that addressed this problem. Instead, the questions/answers kept addressing the scenario of creating a model as well as its associations on one form (using nested_attributes).

1

There are 1 answers

0
Ruby_Pry On

I must attribute the answer to a Ryan Bates' post from 2007 http://archive.railsforum.com/viewtopic.php?id=2696.

Your controller

 def new
   @owners = Array.new(3) { Owner.new } # set up any defaults here
 end

 def create
   @owners = params[:owners].values.collect { |owner| Owner.new(owner) }
   if @owners.all?(&:valid?)
     @owners.each(&:save!)
     redirect_to :action => 'index'
   else
     render :action => 'new'
   end
 end

Your View - new.erb.html

 <% form_tag :action => 'create' do %>
 <% @owners.each_with_index do |owner, index| %>
   <% fields_for "owners[#{index}]", owner do |f| %>
     First Name: <%= f.text_field :firstname  %>
     Last Name: <%= f.text_field :lastname  %>
   <% end %>
 <% end %>
        <%= submit_tag %>
 <% end %>