Codebite: Generic “New Today” for Rails Records
Often times in an application you might want to know how many of a given model were created today. Rather than writing a custom method for each model, let’s keep it DRY and extend ActiveRecord:
class ActiveRecord::Base def self.new_today if self.new.respond_to?(:created_at) self.count(:all, :conditions => "created_at > (NOW() - 60*60*24)") else nil end end end
This will return the number of records created in the last 24 hours by calling the model with
User.new_today). It will return nil if the model does not respond to the
created_at Rails timestamp attribute.