Wednesday, August 15, 2012

Update Legacy Timestamps, Datestamps, and Datetimestamps in ActiveRecord/Rails

ActiveRecord/Rails comes with a way to set the primary key and table name of a model that is using a legacy database table. In ActiveRecord/Rails 3.2, this is done via:

self.primary_key = :foobar_id
self.table_name = :foobar

But, ActiveRecord/Rails 3.2 does not yet provide class attributes to set what columns should be updated with the date, time, or datetime on create or update of the model. There are ways to change this, but a clean, lightweight alternative is the custom_timestamps gem, which allows you to set updated and created timestamp columns with class accessors also:

self.created_timestamp :manufactured_on
self.updated_timestamp :modded_on

It also supports updating multiple columns.

self.created_timestamp [:manufactured_on, :amalgamated_at]
self.updated_timestamp [:redesigned_at, :redesign_release_date]
Check it out on GitHub and let me know if you have any comments or suggestions for it.

No comments: