Gmane
Gravatar
From: Jeremy Kemper <jeremy@...>
Subject: Re: ActiveRecordStore with latest rails and actionpack
Newsgroups: gmane.comp.lang.ruby.rails
Date: 2005-04-03 07:50:17 GMT (3 years, 27 weeks, 6 days, 19 hours and 22 minutes ago)
Peter-Frank Spierenburg wrote:
>> created_at and updated_at are optional, but they're updated for free by
>> Active Record and nice to have for selectively clearing stale sessions.
>>
> Is this in the docs somewhere? This would be a very useful feature for
> my application. Besides id, created_at, and updated_at, what field names
> have special properties?

Timestamping callbacks are set up by default for columns named
created_at/created_on and updated_at/updated_on.  See
http://rails.rubyonrails.com/classes/ActiveRecord/Timestamp.html

Callbacks let you set up "triggers" like this easily.  You can
reimplement timestamping yourself:
  class Foo < ActiveRecord::Base
    before_create { |foo| foo.created_at = Time.now }
    before_save   { |foo| foo.updated_at = Time.now }
  end

Wonderful!  Now say we want timestamps in our other models.  Let's make
a module to mix in the behavior:
  module Timestamped
    # Invoked when "include Timestamped" is called in base_class.
    def self.append_features(base_class)
      base_class.before_create { |model| model.created_at = Time.now }
      base_class.before_save   { |model| model.updated_at = Time.now }
    end
  end

  class Foo < ActiveRecord::Base
    include Timestamped
  end

Then say this is so useful we'd like to add it to any models with these
columns:
  module Timestamped
    def self.append_features(base)
      base.before_create do |model|
        model.created_at ||= Time.now if model.respond_to?(:created_at)
      end
      base.before_save do |model|
        model.updated_at = Time.now if model.respond_to?(:updated_at)
      end
    end
  end

  class ActiveRecord::Base
    include Timestamped
  end

Best,
jeremy