Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Form for creating multiple entries of same model

I am new to rails and I am struggling to design a form. I have model and a controller for "User". I have created a form which accepts one user at a time. What I am trying to create is a form to accept multiple user 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

Form 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 Nested form. If you see the link the tutorial shows how to create multiple questions for a survey. What I want is to create multiple surveys in the same form.

like image 933
theHumbleProgrammer Avatar asked Nov 26 '14 07:11

theHumbleProgrammer


1 Answers

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 controller you should create @users instead of one single @user in new method, and in create method to accept multiple users instead one.

UPDATE:

when you want to update your users in controller, you can do like (I didn't test it):

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

and to create:

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

params[:users].keys should be hash of user ids and params[:users].values should be hash of attributes of corresponding users

I don't know how you plan to manage of dynamic number of users, but maybe this could help.

like image 187
Marko Krstic Avatar answered Oct 27 '22 20:10

Marko Krstic