为 Rails 中的编辑表单提取集合中嵌套资源的 ID

Pulling the id of a nested resource in a collection for the edit form in Rails

我有两个模型:

class Team < ActiveRecord::Base
  belongs_to :scoreboard
end

class Scoreboard < ActiveRecord::Base
  has_many :teams
end

在计分板的 show 页面上,我渲染了以下内容:

<div class="all-teams"> 
  <%= render @scoreboard.teams %>
</div>

其中 links 到执行以下操作的团队目录中的部分内容:

<%= div_for team, :class => "team-list" do %>
  <div class= "boxin1"><%= team.name %></div>
  <div class= "boxin2"><%= team.win %></div>
  <div class= "boxin2"><%= team.loss %></div>
  <div class= "boxin2"><%= team.tie %></div>
  <span class= "boxin3 btn btn-primary"><%= link_to "Edit", edit_scoreboard_team_path(@scoreboard, team.id) %> </span>
  <span class= "boxin3 btn btn-primary">Del</span>
<%end%>

在我提问之前,我也会展示相关操作的控制器数据:

计分板控制器中的显示动作:

def show
  @scoreboard = Scoreboard.find_by(params[:id])
  @team = @scoreboard.teams.build
end

重要提示 这个记分牌#show 视图页面上已经存在一个表单,它创建一个新的团队对象并在团队控制器中调用 team#new 方法和 team#create 方法。这就是为什么在 scoreboard#show 方法中有一个@team 变量。

团队控制器中的编辑操作

def edit
  @scoreboard = Scoreboard.find(params[:scoreboard_id])
  @team = @scoreboard.teams.find(params[:id])
end

现在这是我的问题。每次为每个团队生成 div 时,也会在 div 旁边生成一个编辑按钮,它将带您进入包含用于编辑该特定团队的表单的编辑视图。编辑 link 中的 @scoreboard:scoreboard_id 很好,但似乎我们无法拉:id 每个团队,以便编辑 link 工作。每次我们尝试访问 scoreboard#show 的视图时,我们都会收到以下错误:

没有路由匹配 {:action=>"edit", :controller=>"teams", :id=>nil, :scoreboard_id=>"7 "} 缺少必需的键:[:id]

我们如何为 div_for 中的每个团队提取 :id?

很有可能您正在超越一个新初始化的团队以及其他计分板团队。在呈现您的团队之前尝试拒绝新记录:

<div class="all-teams"> 
 <%= render @scoreboard.teams.reject(&:new_record?) %>
</div>