首页 > 解决方案 > 如何在rails关联中打印多个表格的数据?

问题描述

我已经创建了项目、阶段、任务和 sub_task 脚手架。项目与阶段有一对多关联,阶段与任务有一对多关联,任务与子任务有一对多关联。我想在 project#show 中渲染每个任务的所有 sub_task,目前我能够将所有 sub_tasks 渲染到每个任务。

路线.rb

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

项目控制器.rb

  def show
    @project = Project.includes(stages: :tasks).find(params[:id])
    @stages = @project.stages
    @sub_tasks = SubTask.all
  end

标签: ruby-on-railsruby-on-rails-5

解决方案


您可以包括subtasks以下tasks内容:

 def show
    @project = Project.includes({stages: {tasks: :sub_tasks}}).find(params[:id])
    @stages = @project.stages
    # Now when you iterate through stages, you can fetch tasks associated with each stage, and for each task, you can get subtasks. All of this happens without additional DB queries because of the "includes"
  end

这将获取与项目相关的所有阶段,与每个阶段相关的所有任务,然后是与每个任务相关的子任务!


推荐阅读