首页 > 解决方案 > 如何在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>

标签: ruby-on-rails

解决方案


使用您拥有的嵌套资源路线,我猜 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)

推荐阅读