Automating Record Timestamping

Problem

It's often helpful to know when individual records in your database were created or updated. You want a simple way to collect this data without having to write code to track it yourself.

Solution

You can have Active Record automatically track the creation and modification times of objects by adding date columns named created_on or updated_on to your database tables. datetime columns named created_at and updated_at are kept automatically updated the same way.

class CreateUsers < ActiveRecord::Migration
 def self.up
 create_table :users do |t| 
 t.column :name, :string
 t.column :email, :string
 t.column :created_at, :datetime
 t.column :updated_at, :datetime
 end 
 end 
 def self.down
 drop_table :users
 end 
end

Discussion

From the Rails console, you can see that the presence of the specially named date or datetime columns trigger Active Record's time tracking behavior. By convention, updated_on and created_on are for date fields, and updated_at and created_at are for datetime fields, but the distinction does not appear to be enforced by Active Record, and either will work.

>> User.create :name => "rob", :email => "rob@tupleshop.com"
=> #<User:0x2792178 @errors=#<ActiveRecord::Errors:0x278e910 @errors={}, 
 @base=#<User:0x2792178 
...>>, @attributes={"created_at"=>Tue Sep 19 23:45:36 PDT 2006, "name"=>"rob", 
"updated_at"=>Tue Sep 19 23:45:36 PDT 2006, "id"=>1, "email"=>"rob@orsini.us"}, 
@new_record=false>

The default timestamp recorded for these columns is based on local time. To use UTC, set the following environment.rb option to :utc:

ActiveRecord::Base.default_timezone = :utc

If your database has these columns, this behavior is turned on by default. If you want to disable this behavior in your application, set the following option to false in environment.rb:

ActiveRecord::Base.record_timestamps = false

You can also disable the behavior at the individual class level:

class User < ActiveRecord::Base
 self.record_timestamps = false
 # ...
end

See Also