【发布时间】:2023-03-17 08:59:01
【问题描述】:
我正在构建一个 Rails 4 应用程序,其中有 2 个模型和 1 个用于关联:
游戏.rb
class Game < ActiveRecord::Base
has_many :participations
has_many :players, :through => :participations
accepts_nested_attributes_for :participations, :allow_destroy => true
accepts_nested_attributes_for :players
end
播放器.rb
class Player < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
has_many :participations
has_many :games, :through => :participations
accepts_nested_attributes_for :participations, :allow_destroy => true
accepts_nested_attributes_for :games
end
参与.rb
class Participation < ActiveRecord::Base
belongs_to :player
belongs_to :game
accepts_nested_attributes_for :game
end
这个想法是,几乎每天都在玩游戏,玩家每场比赛都会获得分数(这保留在参与模型中)。
如果我进入游戏页面选择一个游戏并查看所有参与该游戏的玩家及其得分,一切正常。
我似乎无法在游戏节目页面上添加玩家和他们的分数。 与球员列表后,想要一个带有选择器(选择球员姓名)和输入分数的文本框的表格。
如果这可以用 Ajax 来完成会更好。
任何帮助将不胜感激。
更新:
我在我的显示视图中有这个来显示玩家和他们的分数:
<% @game.participations.each do |participation| %>
<tr>
<td><%= participation.player.name %></td>
<td><%= participation.score %></td>
<td><%= participation.time %></td>
</tr>
<% end %>
更新 2
所以我的 Game#show 页面看起来像这样:
<p id="notice"><%= notice %></p>
<p>
<strong>Date:</strong>
<%= @game.date %>
</p>
<p>
<strong>Time:</strong>
<%= @game.time %>
</p>
<%= link_to 'Edit', edit_game_path(@game) %> |
<%= link_to 'Back', games_path %>
<hr>
<h4>Players</h4>
<hr>
<table class="table table-condensed">
<thead>
<tr>
<th>Player</th>
<th>Score</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<% @game.participations.each do |participation| %>
<tr>
<td><%= participation.player.name %></td>
<td><%= participation.score %></td>
<td><%= participation.time %></td>
</tr>
<% end %>
</tbody>
</table>
<%= form_for :participation, :url => participations_path, :html => {:method => :post} do |f| %>
<table>
<tr>
<td><%= f.collection_select :player_id, Player.all, :id, :name %></td>
<td><%= f.text_field :score %></td>
<td><%= f.text_field :time %></td>
</tr>
</table>
<%= f.submit %>
<% end %>
现在一切正常,但我如何将 game_id 传递给表单,因为我在 Game#show 视图中我有 @game.id 我尝试过类似的操作但不起作用:
<%= form_for :participation, :url => participations_path, :html => {:method => :post}, :game_id => @game.id do |f| %>
【问题讨论】:
-
查看cocoon gem。
-
@nathanvda 我会去看看,让你知道。
-
我试过 cocoon 但我得到这个错误 undefined method `reflect_on_association' for NilClass:Class
标签: ruby-on-rails model-associations