繁体   English   中英

我如何在 rails 中通过 id 呈现两个表的内容

[英]how can i render content of two table by id in rails

我在 Rails 中有两个项目,阶段和任务脚手架。 i project 与 stage 有一对多的关联,stage 与 task 有一对多的关联。 我在 project#show 中使用关联阶段渲染项目,但我无法通过其关联阶段渲染任务。 目前所有任务都会在每个阶段呈现。 路由文件

resources :projects do
    resources :stages do
      resources :tasks
    end
  end

project_controller.rb

  def show
    @project = Project.includes(:stages).find(params[:id])
    @stages = @project.stages
    @tasks = Task.all
  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>Task Name</th>
        <th>Planned start date</th>
        <th>Planned end date</th>
      </tr>
    </thead>

    <tbody>
      <% @stages.each do |stage| %>
        <tr class="stage">
          <td><%= stage.stage %></td>
          <td><%= stage.planned_start_date.strftime("%d-%m-%Y") %></td>
          <td><%= stage.planned_end_date.strftime("%d-%m-%Y") %></td>   
          <% end %>
        </tr>

        <% @tasks.each do |task| %>
          <tr>
            <td><%= task.task_name %></td>
            <td><%= task.planned_start_date.strftime("%d-%m-%Y") %></td>
            <td><%= task.planned_end_date.strftime("%d-%m-%Y") %></td>
          </tr>
        <% end %>
      <% end %>
    </tbody>
  </table>
</div>

假设你已经有has_many :tasks in stage,你可以通过对应的关联获取每个 stage 的任务。

要避免每个阶段的 N+1 条件预加载任务:

@project = Project.includes(stages: :tasks).find(params[:id])

并在您查看它们的循环中:

<% stage.tasks.each do |task| %>
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM