jedi
jedi

Reputation: 2198

Create multiple users in one form

I have Event model and a show page which shows the @event page and the customer registration form.

Now, my client wants a form for a different kind of event, which would have customer fields as well but labeled not customer name but parent / carer's name (similar form for a customer) and he also wants a Add player button on the bottom which would allow the parent /carer to add max 3 players. So the buisness need is that a parent registers 'players'. It should be possible to add max 3 players. I am wondering how I could go about creating 4 customers in one form. To me it sounds a bit odd, to be honest. Is this even possible? Or should I introduce Parent model and a Player model and connect them with each other. So for specific kinds of events I would create a Parent/Carer and max 3 players.

<%= simple_form_for @customer do |f| %>
 ...
<% end %>

Upvotes: 0

Views: 423

Answers (1)

xploshioOn
xploshioOn

Reputation: 4115

There is no complete details to give you an specific solution, but will guide you in the right direction to solve it with an example.

Let's say you have your Parent model and your players model, you want to add a parent with 3 players in the same form.

we define in your parent models that you can accept nested attributes for your players, so for example if you want to create a parent with some players, you can do something like Parent.create(params_with_players_too) and it will create the parent and create the players too, associated with that parent. of course, having in mind that the params comes in the correct way.

Class Parent < ActiveRecord::Base
  has_many :books
  accepts_nested_attributes_for :players
end 

Class Player < ActiveRecord::Base
  belongs_to :parent
end

after that, your form could be something like

<%= form_for @parent do |f| %>
  <%= f.fields_for :players, [Player.new]*3 do |player| %>
    <%= player.text_field :name %>
  <% end %>
  <%= f.submit %>
<% end %>

and in your controller, you have to permit the players params too, something like this

def create
    @parent = Parent.new(parent_params)
    if @parent.save
    ...
end

def parent_params
  params.require(:parent).permit(:attribute1, players_attributes: [:id, :name])
end

of course, you will have to understand it and adapt it to your specific case, hope that this helps you.

Upvotes: 1

Related Questions