我正在我的 rails 应用程序中设置嵌入式表单。
这不起作用
<h1>PlayersToTeams#edit</h1>
<%= form_for @players_to_teams do |field| %>
<%= field.fields_for @players_to_teams.player do |f| %>
<%= f.label :IsActive %>
<%= f.text_field :IsActive %>
<% end %>
<%= field.label :BT %>
<%= field.text_field :BT %>
<br/>
<%= field.submit "Save", class: 'btn btn-primary' %>
<% end %>
给我一个ActiveRecord::AssociationTypeMismatch
错误。注意行@players_to_teams.player
中的forms_for
。
这确实有效:
<h1>PlayersToTeams#edit</h1>
<%= form_for @players_to_teams do |field| %>
<%= field.fields_for :player do |f| %>
<%= f.label :IsActive %>
<%= f.text_field :IsActive %>
<% end %>
<%= field.label :BT %>
<%= field.text_field :BT %>
<br/>
<%= field.submit "Save", class: 'btn btn-primary' %>
<% end %>
注意线路:player
中的呼叫fields_for
。
使用符号和使用实例有什么区别?我想我会想在这种情况下使用一个实例,但我猜不是?
编辑
楷模:
class Player < ActiveRecord::Base
has_many :players_to_teams
has_many :teams, through: :players_to_teams
end
class PlayersToTeam < ActiveRecord::Base
belongs_to :player
belongs_to :team
accepts_nested_attributes_for :player
end
控制器:
class PlayersToTeamsController < ApplicationController
def edit
@players_to_teams=PlayersToTeam.find(params[:id])
end
def update
@players_to_teams=PlayersToTeam.find(params[:id])
respond_to do |format|
if @players_to_teams.update_attributes(params[:players_to_team])
format.html { redirect_to @players_to_teams, notice: 'Player_to_Team was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @players_to_teams.errors, status: :unprocessable_entity }
end
end
end
end
示例项目
Github:https ://github.com/workmaster2n/embedded-form-errors