我已经创建了项目,阶段,任务和子任务支架。项目与阶段具有一对多的关联,阶段与任务具有一对多的关联,而任务与子任务具有一对多的关联。我想在project#show中呈现每个任务的所有sub_task,目前我能够呈现每个任务的所有sub_tasks。
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
您可以如下将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
这将获取与项目相关的所有阶段,与每个阶段相关的所有任务,然后与每个任务相关的子任务!