I'm putting together a way for teams to enter sporting tournaments. When entering a team, the user must also register all the players for that team. My associations & routes are setup as follows:
class Tournament < ApplicationRecord
has_many :teams
has_many :players, :through => :teams
accepts_nested_attributes_for :teams
end
class Team < ApplicationRecord
belongs_to :tournament
has_many :players
accepts_nested_attributes_for :players
end
class Player < ApplicationRecord
belongs_to :team
has_one :tournament, :through => :team
end
(routes.rb)
resources :tournaments do
resources :teams, :only => [:new, :create] do
resources :players, :only => [:new, :create]
end
end
What I would like to have is one form with multiple Player inputs that are all saved with one click. My current controller & new.html.erb are as follows:
(players_controller.rb)
class PlayersController < ApplicationController
def create
@tournament = Tournament.find_by_id params[:tournament_id]
@team = Team.find_by_id params[:team_id]
@player = @team.players.new(player_params)
if @player.save
redirect_to root_path #just return home for now
else
redirect_to new_tournament_team_path(@tournament)
end
end
def new
@tournament = Tournament.find_by_id params[:tournament_id]
@team = Team.find_by_id params[:team_id]
@player = []
3.times do
@player << @team.players.new
end
end
private
def player_params
params.require(:player).permit(:name, :tournament_id, :team_id)
end
end
(players/new.html.erb)
<%= form_for [@tournament, @team, @player] do |f| %>
<% hidden_field_tag :tournament_id, @tournament.id %>
<% hidden_field_tag :team_id, @team.id %>
<% 3.times do %>
<p>
<%= f.label :name, "Name: " %>
<%= f.text_field :name %>
</p>
<% end %>
<%= submit_tag 'Submit', :class => 'rounded_btn' %>
</p>
<% end %>
From my understanding I should be trying to create an array of "players" that would contain the names of the 3 players that are entered in the form. This array then gets saved by the create action. Is that the right way to go about it, and what might need changing in my code to set me on the right path?
Thanks.
FIXED
Applied the methods in Ryan Bate's Nested Model Form tutorial
Also removed validation for "belongs_to" in Rails 5.0