Back to Blog

Get in Touch

Codebite: Generic "New Today" for Rails Records

By Michael Bleigh February 25, 2008 in rails, ActiveRecord, codebites, new records

Missing

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 new_today (e.×. User.new_today). It will return nil if the model does not respond to the created_at Rails timestamp attribute.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...