0
我正在为团队提供一种进入体育比赛的方式。在进入球队时,用户还必须注册全部该球队的球员。我协会&路线是设置如下:form_for深层嵌套路线的多个实例
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
我想有一个窗体,这些都保存与点击多个玩家输入。我的电流控制器& new.html.erb如下:
(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
(播放器/ 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 %>
从我的理解我应该试图创建一个“球员”阵列,其中将包含输入表单中的3名球员的名字。这个数组然后被创建操作保存。这是否是正确的方式去解决这个问题?为了让我走上正确的道路,可能需要改变我的代码?
感谢。
FIXED
施加的方法在Ryan Bate's Nested Model Form tutorial
另外removed validation for "belongs_to"在滑轨5.0