如何计算 current_level 6 的实例?

How to .count instances of current_level 6?

我正在尝试 .countcurrent_level 上,具体是在 6habit.rb中的方法应该怎么写?

def current_level
        return 0 unless date_started
      def committed_wdays
        committed.map do |day|    
          Date::ABBR_DAYNAMES.index(day.titleize)
        end
      end

      def n_days
        ((date_started.to_date)..Date.today).count do |date| 
          committed_wdays.include? date.wday
        end - self.real_missed_days
      end     

  case n_days     
      when 0..9
        1
      when 10..24
        2
      when 25..44
        3
      when 45..69
        4
      when 70..99
        5
      else
        6 #how can we count all the habits that are on this level?
    end
end

然后我将在 application_controller 中调用该方法,以便我可以在边栏中使用该方法。

如果您需要进一步的代码或解释,请告诉我。非常感谢!

.count 可以接受一个参数,该参数是您要计算的值。因此,例如,如果您想要一份习惯列表,并且您对每个习惯都调用了 current_level:

>> levels = habits.map(&:current_level)
=> [5, 3, 1, 1, 1, 2, 6, 5, 4, 6]

并且您想计算列表中 6 的数量,您可以这样做:

>> levels.count(6)
=> 2

此外,如果您想获得所有级别的计数:

>> Hash[*a.group_by(&:itself).flat_map{|k,v| [k, v.size]}]
=> {5=>2, 3=>1, 1=>3, 2=>1, 6=>2, 4=>1}

假设 Habit 是一个模型,在 habit.rb 中,并且 Habit 中的所有习惯都属于一个用户,这应该适合你:

class Habit < ActiveRecord::Base
  # other methods ...
  # Since it's a class method, you call Habit.best_habits.
  def self.best_habits_count
      all.count { |habit| habit.current_level == 6 }
  end
  # other methods ...
end

如果他们属于不同的用户,您需要在您的user.rb中添加,例如:

class User < ActiveRecord::Base
  # other methods ...    
  # call : user.best_habits_count
  def best_habits_count
    habits.count { |habit| habit.current_level == 6 }
  end
  # other methods ...
end

更新

ActiveRecord::Associations::CollectionProxy 有自己的计数方法,不同于 Array#count,它不占用块。因此,给定的块将被忽略,它简单地 returns 调用时不带任何参数的集合中的记录数。

此处有更多信息:ActiveRecord::Associations::CollectionProxy Ruby Rails api。

所以解决办法就是用另一种方法来计算它们。

最终解决方案

输入user.rb:

  def count_mastered
    @res = habits.reduce(0) do |count, habit|
      habit.current_level == 6 ? count + 1 : count
    end
  end

你需要做这样的事情:

  1. GET 你的 user
  2. 的所有 habit
  3. 检查 habitcurrent_level == 6
  4. 将其添加到 counter 变量

如果你真的想使用 .count 方法:

  1. GETuser 的所有 habit.current_level 并将其保存到 array

  2. 对那个数组使用.count6

希望这能让您走上正确的道路:)