Question

I'm creating an activity chart, showing the number of records saved to a user's profile over time (in this case its 'user.notes' i.e. user has_many notes). The json output from the function below feeds nicely into a chart library.

The function below however does not output data for weeks without any activity...I need these 'holes', with correct week dates to be in there... can anyone suggest how I might be able to do this?

I believe the 'has_activity' gem has this functionality, however I would prefer to avoid using a whole gem to do this.

class Case < ActiveRecord::Base 
 def self.user_activity_profile(user)
    array = []
    user.notes.group_by{ |u| u.created_at.beginning_of_week }.each do |week, entries|
      array << { week: week.strftime("%d %b"), count: entries.count }
    end
    array.to_json
  end
end
Was it helpful?

Solution 2

  def self.user_activity_profile(user)
    from = Time.now - 1.months
    to = Time.now
    tmp = from
    array = []
    begin
       tmp += 1.week
        array << [
          week: tmp.strftime("%d %b"), 
          count: user.notes.where("created_at BETWEEN ? AND ?", tmp, tmp + 1.week).count
        ]
    end while tmp <= to
    array.to_json
  end

OTHER TIPS

I believe this should do what you're looking for. It just takes the first and last note for each user and then steps through the date range by 7 days at a time which forces it not to skip any weeks.

class Case < ActiveRecord::Base 
  def self.user_activity_profile(user)
    array = []
    notes = user.notes
    first = notes.first.created_at.beginning_of_week
    last = notes.last.created_at.beginning_of_week
    (first..last).step(7){ |date| 
      array << [
        week:date.strftime("%d %b"), 
        count: notes.where("created_at BETWEEN ? AND ?", date, date + 1.week).count
      ]}
    array.to_json
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top