Repopulating Rails form for an array of objects -


i want create multiple user objects using 1 form. have form looks this:

= form_for @users, :url => "batch_add" |f|   - @users.each_with_index |user, index|     = fields_for "i-dont-know what-goes-here" |u|       = render :partial => "user_fields", :locals => {:i => index} 

i have 2 methods in users controller follows. first method (batch_add_new) called when form first loaded (get), , second method (batch_add_create) called when form submitted (post).

def batch_add_new   @users = [user.new] end  def batch_add_create   @users = []   = 0   while(!params["user_" + i.to_s].nil?)     u = user.new(params["user_" + i.to_s])     @users << u     = + 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 submit form, params (if had tried add 2 users):

{...,"user_0"=>{"role_id"=>"1","name"=>"x"},  "user_1"={"role_id"=>"2","name"=>"y"}, ...} 

what should pass fields_for such form work , fields re-populate on failed validation? have tried passing in users[], user suggested in multiple objects in rails form can't seem syntax right.

i solved re-factoring form represent single object model, accepts nested attributes user (as suggested in link posted in question [here]). end model in database (and files controller/views), controller code cleaner , able make more use of rails magic.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -