我有三个类:玩家、团队和游戏。
玩家在一个团队中比赛,每场比赛都有多个团队相互对抗。
我有一个嵌套的表单,它应该使用强大的参数一次性创建玩家、团队和游戏。如果我只是在创建游戏,甚至当我创建游戏和团队时,这是有效的。然而,一旦玩家被添加到组合中,ActiveRecord::RecordInvalid (Validation failed: Players team must exist).
的整个过程就会失败
任何想法都将不胜感激。
我的型号:
class Game < ApplicationRecord
has_many :teams
has_many :players, through: :teams
accepts_nested_attributes_for :teams, :players
end
class Team < ApplicationRecord
belongs_to :game
has_many :players
accepts_nested_attributes_for :players
end
class Player < ApplicationRecord
belongs_to :team
end
我的游戏控制器:
class GamesController < ApplicationController
def new
@game = Game.new
@team = @game.teams.build
@player = @game.players.build
end
def create
@game = Game.new(game_params)
if @game.save
flash[:success] = "Booking successful!"
redirect_to root_path
else
render 'new'
end
end
private
def game_params
params.require(:game).permit(:start_time, teams_attributes: [:name], players_attributes: [:first_name])
end
end
最后,我的表单部分:
<%= form_with model: @game do |f| %>
<%= f.fields_for :players do |f_players| %>
<%= f_players.label :first_name %>
<%= f_players.text_field :first_name %>
<% end %>
<%= f.fields_for :teams do |f_teams| %>
<%= f_teams.label :name, "Team name" %>
<%= f_teams.text_field :name %>
<% end %>
<%= f.label :start_time, "Game date" %>
<%= f.date_field :start_time %>
<%= f.submit "Confirm" %>
<% end %>
您试图建立多个团队,每个团队都有多个玩家。然而,你试图让所有球员都处于同一水平,所以rails不知道他们应该加入哪支球队。
如果我们要以一种长期的方式来做这件事,我们会创建团队并列出其中的球员
<%= form_with model: @game do |f| %>
<%= f.fields_for :teams do |f_teams| %>
<%= f_teams.label :name, "Team name" %>
<%= f_teams.text_field :name %>
<%= f_teams.fields_for :players do |f_players| %>
<%= f_players.label :first_name %>
<%= f_players.text_field :first_name %>
<% end %>
<% end %>
<%= f.label :start_time, "Game date" %>
<%= f.date_field :start_time %>
<%= f.submit "Confirm" %>
<% end %>
问题是,球队和球员都需要允许1+的记录。要做到这一点,你需要使用JS来添加一个新团队或一个新玩家。必须保留和验证他们所连接的团队。
你可能会发现这些文章很有帮助:
- https://stevepolito.design/blog/create-a-nested-form-in-rails-from-scratch/
- https://levelup.gitconnected.com/the-many-things-about-nested-form-in-ruby-on-rails-15f32ed66446