D-Nice
D-Nice

Reputation: 4870

Rails - How to check what the record count of a model 24 hours ago

I want to display the rate of change in the total number of records for a certain model. So I need to know, at any given time, how many there were 24 hours ago, and how many there are now. It is very likely that a record will be deleted by users, so I can't just use the value of existing records that are older than 24 hours.

Is there a simple way to do this?

Thanks

Upvotes: 1

Views: 2678

Answers (2)

Chamnap
Chamnap

Reputation: 4766

Well, you could do a count against the column created_at.

def count_rate(model, time=DateTime.now)
  current_count = model.count(:conditions => ["created_at < ?", time])
  last_24_hours_count = model.count(:conditions => ["created_at < ?", time-24.hours])

  current_count - last_24_hours_count
end

This method count the record at a given compared with the last 24 hours.

Well, in case the user has deleted those records back, you would should create another table Rate(date, hour, count) and record every hour by using observer (only after_create).

def after_create
  rate = Rate.find_or_initialize_by(Date.today.to_s, Time.now.hour)
  rate.increment(:count)
  rate.save!
end

In this observer, if it finds the existing record by date and hour, it simply increment the count column. You add the default value to zero on count column as well. Later on, you can query the data from that table by date and hour.

Upvotes: 1

Amol Pujari
Amol Pujari

Reputation: 2349

class Item < ActiveRecord::Base
  scope :since, lambda {|time| where("created_at > ?", time) }
  scope :during_last, lambda {|time| where("created_at > ?", (Time.now - time)) }
end

Item.since(Time.now - 24.hours).count
Item.since(24.hours.ago).count
Item.during_last(24.hours).count

Upvotes: 3

Related Questions