如何在Rails关联中从多个表打印数据?

问题描述 投票:0回答:1

我已经创建了项目,阶段,任务和子任务支架。项目与阶段具有一对多的关联,阶段与任务具有一对多的关联,而任务与子任务具有一对多的关联。我想在project#show中呈现每个任务的所有sub_task,目前我能够呈现每个任务的所有sub_tasks。

output

routes.rb

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

projects_controller.rb

  def show
    @project = Project.includes(stages: :tasks).find(params[:id])
    @stages = @project.stages
    @sub_tasks = SubTask.all
  end
ruby-on-rails ruby-on-rails-5
1个回答
1
投票

您可以如下将subtaskstasks包括在内:

 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

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

© www.soinside.com 2019 - 2024. All rights reserved.