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

Share:

1 Response to “Codebite: Generic "New Today" for Rails Records”

  1. Brian

    List<%= train.updated_at.to_formatted_s(:short)%> This returns the correct result List<%= train.created_at.to_formatted_s(:short)%> missing attribute: created_at List<%= train.created_at %> missing attribute: created_at This field is populated correctly in the DB ?? Rails 2.0.2 Is this something New ? If you could point me in the correct direction


Leave a Reply