0

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.

Community
  • 1
  • 1
Adam
  • 2,214
  • 1
  • 15
  • 26

1 Answers1

0

I solved this by re-factoring my form to represent a single object model, which accepts nested attributes for user (as suggested in the link I posted in the question [here]). I end up with an extra model in my database (and extra files for controller/views), but the controller code is much cleaner and I am able to make more use of rails magic.

Community
  • 1
  • 1
Adam
  • 2,214
  • 1
  • 15
  • 26