2017-03-09 30 views
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

回答