ruby on rails - How to .count instances of current_level 6? -


i'm trying .count on current_level when it's @ 6. how should write method in habit.rb?

def current_level         return 0 unless date_started       def committed_wdays         committed.map |day|               date::abbr_daynames.index(day.titleize)         end       end        def n_days         ((date_started.to_date)..date.today).count |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 count habits on level?     end end 

i call method in application_controller may use method in sidebar.

please let me know if need further code or explanation. thank much!

assuming habit model, inside habit.rb, , habits in habit belong single user, should work :

class habit < activerecord::base   # other methods ...   # since it's class method, call habit.best_habits.   def self.best_habits_count       all.count { |habit| habit.current_level == 6 }   end   # other methods ... end 

if belong different users, need add in user.rb , instance :

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 

update

activerecord::associations::collectionproxy has own count method different array#count , doesn't take block. because of that, block given ignored , simple returns number of records in collection when called without arguments.

more info here : activerecord::associations::collectionproxy on ruby on rails api.

so solution use way count them.

final solution

put in user.rb:

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

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -