如何在 rails 关联中打印数据形成多个 table?
how can print data form multiple table in rails association?
我已经创建了项目、阶段、任务和 sub_task 脚手架。项目与阶段具有一对多关联,阶段与任务具有一对多关联,任务与子任务具有一对多关联。我想在项目#show 中渲染每个任务的所有 sub_task,目前我能够为每个任务渲染所有 sub_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
您可以将 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
这将获取与项目相关的所有阶段、与每个阶段相关的所有任务,然后是与每个任务相关的子任务!
我已经创建了项目、阶段、任务和 sub_task 脚手架。项目与阶段具有一对多关联,阶段与任务具有一对多关联,任务与子任务具有一对多关联。我想在项目#show 中渲染每个任务的所有 sub_task,目前我能够为每个任务渲染所有 sub_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
您可以将 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
这将获取与项目相关的所有阶段、与每个阶段相关的所有任务,然后是与每个任务相关的子任务!