i have created project, stage, task and sub_task scaffold. project has one to many association with stage, stage has one to many association with task and task has one to many association with sub task. i want to render each task's all sub_task in project#show, currently i am able to render all sub_tasks to each task.
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
You can include the subtasks
along with tasks
as follows:
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
This would fetch all stages related to a project, all tasks related to each stage, and then sub tasks related to each task!