我是一个热心的 Rails 新手,试图弄清楚如何编辑 has-many-through 连接表中的字段。
我有三个模型。
球员模型:
# == Schema Information
#
# Table name: players
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Player < ActiveRecord::Base
attr_accessible :name
has_many :appearances #, :dependent => true
has_many :games, :through => :appearances
accepts_nested_attributes_for :games
accepts_nested_attributes_for :appearances
end
游戏模型:
# == Schema Information
#
# Table name: games
#
# id :integer not null, primary key
# team :string(255)
# date :date
# created_at :datetime not null
# updated_at :datetime not null
# game_innings :integer
#
class Game < ActiveRecord::Base
attr_accessible :date, :team, :game_innings
has_many :appearances #, :dependent => true
has_many :players, :through => :appearances
accepts_nested_attributes_for :players
accepts_nested_attributes_for :appearances
end
还有一个外观模型:
# == Schema Information
#
# Table name: appearances
#
# id :integer not null, primary key
# player_id :integer not null
# game_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# innings_played :integer
#
class Appearance < ActiveRecord::Base
attr_accessible :player_id, :game_id
belongs_to :game
belongs_to :player
end
当我编辑球员时,我希望能够列出和编辑在每场比赛中打过的局,或者更具体地说,我希望列出和编辑每个出场的 innings_played。
我意识到它是不完整的,但这是我的 edit.html.erb 目前的样子:
<h1>Editing player</h1>
<%= form_for(@player) do |f| %>
<% if @player.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@player.errors.count, "error") %> prohibited this player from being saved:</h2>
<ul>
<% @player.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<table>
<tr>
<th>Opponent</th>
<th>Innings Played</th>
</tr>
<% f.fields_for :games do |games_form| %>
<tr>
<td><%= games_form.label :team %></td>
</tr>
<% end %>
</table>
<br>
<br>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Show', @player %> |
<%= link_to 'Back', players_path %>
感谢您可以分享的任何知识。