ruby-on-rails - 如何在rails中渲染多个脚手架表?
问题描述
我分别有三个不同的模型、控制器和视图。它们是项目、阶段和任务。我想在 project_controller#show 中渲染舞台已经完成。项目与阶段是一对多的关系,任务与阶段是多对一的关系。我想渲染每个阶段,然后是他们的任务,等等。我试图这样做,但我遇到了错误。
路线.rb
resources :projects do
resources :stages do
resources :tasks
end
end
项目控制器.rb
def show
@project = Project.includes(:stages).find(params[:id])
@stages = @project.stages
end
项目/show.html.erb
<%= link_to "Add Stage", new_project_stage_url(@project), :class=>"button primary small" %>
<br>
<div class="table-scroll">
<table>
<thead>
<tr>
<th>Stage</th>
</tr>
</thead>
<tbody>
<% @stages.each do |stage| %>
<tr>
<td><%= stage.stage %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
tasks/index.html.erb(我想添加任务按钮,所有与阶段相关的任务都将呈现在表中的项目显示页面上)
<%= link_to 'New Task', new_project_stage_task_url, :class=>"button primary" %>
<div class="table-scroll">
<table>
<thead>
<tr>
<th>Task name</th>
<th>Planned start date</th>
<th>Planned end date</th>
</tr>
</thead>
<tbody>
<% @tasks.each do |task| %>
<tr>
<td><%= task.task_name %></td>
<td><%= task.planned_start_date %></td>
<td><%= task.planned_end_date %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
解决方案
使用您拥有的嵌套资源路线,我猜 tasks#index 的路径将是:
/tasks/:project_id/:stage_id/
为此,您需要始终提供 project_id 和 stage_id 来查看任务。因此,您的 tasks#index 操作应如下所示:
def index
@project = Project.find(params[:project_id])
@stage = @project.stages.find(params[:stage_id])
@tasks = @stage.tasks
end
这样,在您的 tasks/index.html.erb 视图中,您将可以访问 @project 和 @stage 实例变量,并且您可以使用正确的 url:
new_project_stage_task_url(project_id: @project.id, stage_id: @stage.id)
推荐阅读
- java - 通过shell脚本构建maven时出现Hibernate JDBC Connection Exception
- ios - 如何管理企业分发临时配置文件到期?
- html - HTML 中的 URL 和所需链接的 URL 不相同
- awk - 使用 bash 进行基于列和行的修改
- ios - 可以在 xcode 项目文件中使用 fastlane 命令配置 Jenkins 管道
- google-chrome - Codeception,如何填写日期选择器或按数字
- asp.net-core - 确定 [Authorize] 策略失败原因的最佳方法是什么?
- angular - Angular v6 管道(map())问题
- java - 获取当前ec2实例的hostName和Instance Id
- sql - 通过 SQL 生成每个客户每月的销售报告,例如按两列分组并对第三列求和