Rails Form to create multiple records of the same model

I am new to rails and I am struggling to develop a shape. I have a model and controller for "User". I created a form that accepts one user at a time. What I'm trying to create is a form for accepting multiple users from the same page.

def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to @user else render 'new' end end 

Shape in new

 <%= form_for(@user) do |f| %> <%= render 'fields', f: f %> <%= f.submit "Create my account", class: "btn btn-large btn-primary" %> <% end %> 

_fields.html.erb

 <fieldset> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %> <%= f.label :password %> <%= f.password_field :password %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation %> </fieldset> 

Note. I know how to create a Nested Form . If you see a link, this tutorial shows how to create a few survey questions. I want to create several polls in the same form.

+5
source share
1 answer

try to do something like:

 <%= form_tag(some_url_path, method: :put) do %> <% for user in @users %> <%= fields_for "users[]", user do |f| %> <%= render 'fields', f: f, user: user %> <% end %> <% end %> <%= submit_tag "Submit" %> <% end %> 

and in the controller you must create @users instead of one @user method in new , and in the create method accept multiple users instead of one.

UPDATE:

when you want to update your users in the controller, you can do (as I have not tested it):

 User.update(params[:users].keys, params[:users].values) 

and create:

 User.create(params[:users].values) 

params[:users].keys should be a hash of user identifiers, and params[:users].values should be a hash of attributes of the corresponding users

I don’t know how you plan to manage the dynamic number of users, but maybe this can help.

+1
source

Source: https://habr.com/ru/post/1207713/


All Articles