I have generated a project, stage, task, and sub_task scaffold. each project has many stages and each stage has many tasks and each task has many sub_tasks. the corresponding table has been generated in the database. planned start and planned end date field has been added into the stage, task and sub_task table. now I want to add a column on project#index that will show the count of pending stages+tasks+sub_tasks together for each project. I have achieved this goal in project#show but I not able to do that in project#index...
projects_controller.rb
def index
@projects = current_user.projects.all.order("created_at DESC").paginate(page: params[:page], per_page: 15)
end
def show
@project = Project.includes(stages: {tasks: {sub_tasks: {sub_sub_tasks: :sub_three_tasks}}}).find(params[:id])
@stages = @project.stages
@tasks = Task.where(stage_id: @stages.ids)
@sub_tasks = SubTask.where(task_id: @tasks.ids)
stage_counter = 0
task_counter = 0
sub_task_counter = 0
@stages.each{|s| stage_counter += 1 if s.planned_end_date.past? && s.status == 0 || s.planned_end_date.past? && s.status == 2}
@tasks.each{|s| task_counter += 1 if s.planned_end_date.past? && s.status == 0 || s.planned_end_date.past? && s.status == 2}
@sub_tasks.each{|s| sub_task_counter += 1 if s.planned_end_date.past? && s.status == 0 || s.planned_end_date.past? && s.status == 2}
@count = stage_counter + task_counter + sub_task_counter
end
index.html.erb(project)
<table>
<thead>
<tr>
<th>Project Name</th>
<th>Activity Status</th>
</tr>
</thead>
<tbody>
<% @projects.each do |project| %>
<tr>
<td><%= project.project_name %></td>
<td class="alert"><%= @total_count.to_s + " Activity Pending" %></td>
</tr>
<% end %>
</tbody>
</table>
See Question&Answers more detail:os