我创建了一个与projet
有多对一关联的user
支架。项目脚手架与stage
有一对多的关联,阶段与sub_task
有一对多的关联。现在每个支架都具有一个属性planned_end_date
,我想打印阶段号,阶段号和sub_task在选定日期未完成。并将其打印到project#index操作的列中。通过删除@projects.each do |project|
,此代码在project#show操作中效果很好,但是project#index操作中的相同代码在列的每一行中打印相同的数字。
projects_controller.rb(index#Action)
@projects = current_user.projects.all.order("created_at DESC").paginate(page: params[:page], per_page: 15)
@projects.each do |project|
@stages = Stage.where(project_id: @projects.ids )
@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
project#index
<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><%= @count %></td>
</tr>
<% end %>
</tbody>
</table>
Gemfile
ruby '2.6.3'
gem 'rails', '~> 5.2.4'
我想打印未按时完成的每个项目的阶段,任务,子任务的总数。在project#index动作中。谁能知道我在想什么吗?
@ rock,首先,您没有正确使用ruby。
您不需要使用循环和计数器,您可以这样做:
@stages = Stage.where(project_id: @projects.ids ).where("planned_end_date < ?",Time.now).where("status IN (?)", [0,2])
task
和sub_task
的相同方法>
然后
@total_count = @stages.count + @tasks.count + @sub_tasks.count
您一定会得到适当的计数。尝试让我知道您是否遇到任何问题