form_for深层嵌套路由的多个实例

时间:2017-03-09 00:27:54

标签: ruby-on-rails ruby form-for nested-routes

我正在为团队组织一场参加体育比赛的方式。进入团队时,用户还必须为该团队注册所有球员。我的协会&路线设置如下:

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

我想要的是一个包含多个播放器输入的表单,只需单击一下即可保存。我目前的控制器&amp; 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个玩家的名字。然后,该数组由create动作保存。这是正确的方法吗?我的代码中可能需要更改什么才能让我走上正确的道路?

感谢。

固定
应用Ryan Bate's Nested Model Form tutorial中的方法 另外在Rails 5.0中removed validation for "belongs_to"

1 个答案:

答案 0 :(得分:0)

<强>固定
应用Ryan Bate's Nested Model Form tutorial中的方法 另外在Rails 5.0中removed validation for "belongs_to"