I want to create multiple user objects using one form. I have a form which looks like this:
= form_for @users, :url => "batch_add" do |f|
- @users.each_with_index do |user, index|
= fields_for "I-DONT-KNOW WHAT-GOES-HERE" do |u|
= render :partial => "user_fields", :locals => {:i => index}
I have two methods in my Users controller as follows. The first method (batch_add_new) is called when the form is first loaded (GET), and the second method (batch_add_create) is called when the form is submitted (POST).
def batch_add_new
@users = [User.new]
end
def batch_add_create
@users = []
i = 0
while(!params["user_" + i.to_s].nil?)
u = User.new(params["user_" + i.to_s])
@users << u
i = i + 1
end
end
if @users.all?(&:valid?)
@users.all?(&:save)
flash[:notice] = "Users have been sucessfully created!"
redirect_to "/some/path"
else
render :batch_add_new
end
When I submit my form, I get params like this (if I had tried to add two users):
{...,"user_0"=>{"role_id"=>"1","name"=>"X"},
"user_1"={"role_id"=>"2","name"=>"Y"}, ...}
What should I pass into fields_for such that this form will work properly and the fields will re-populate on failed validation? I have tried passing in users[], user
as suggested in Multiple objects in a Rails form but can't seem to get the syntax right.