计数器在Rails应用程序中未按预期方式工作

问题描述 投票:-1回答:1

我创建了一个与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动作中。谁能知道我在想什么吗?

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

@ rock,首先,您没有正确使用ruby。

您不需要使用循环和计数器,您可以这样做:

 @stages = Stage.where(project_id: @projects.ids ).where("planned_end_date < ?",Time.now).where("status IN (?)", [0,2])

tasksub_task的相同方法>

然后

@total_count = @stages.count + @tasks.count + @sub_tasks.count

您一定会得到适当的计数。尝试让我知道您是否遇到任何问题

© www.soinside.com 2019 - 2024. All rights reserved.