Abhimanyu
Abhimanyu

Reputation: 423

insert multiple records to a single table from a single form

Generally if we can create only 1 record, say 1 user at a time from the form. But what if I want to create multiple users from a single form? There are no associations with other models. How can i do that?

Upvotes: 1

Views: 1849

Answers (2)

Amar
Amar

Reputation: 6942

You have to make a form with an array of users params .e.g

<%= from_tag '/users/create_multiple' do %>
 <%= text_field_tag "users[][name]" %>
 <%= text_field_tag "users[][name]" %>
<% end %>

In UsersController:

def create_multiple
 params[:users].each do |user|
  user = User.create(user)
 end
end

You can add validation code as per your wishes, visit here how to pass form params for multiple records http://guides.rubyonrails.org/form_helpers.html#basic-structures

Upvotes: 3

maximus ツ
maximus ツ

Reputation: 8065

One option is, write as many forms that you want for each model and submit all the forms once with Jquery.

This link will help you with submitting multiple forms

Multiple submit buttons/forms in Rails

Upvotes: 1

Related Questions