Disabling Timestamps by Model in Rails 1.2

I recently had a need to disable the timestamp for ‘updated_at’ for one particular little update to a table. At work, we are stuck on Rails 1.2.x for the time being. ActiveRecord::Base does indeed have a class accessor called ‘record_timestamps’ that can be set to true or false. However, in Rails 1.2.x, this is not class inheritable. So, I set about fixing that.

Note: If you are using Rails 2.0.x, you can safely ignore this. You may want to read through Evan Weaver’s ‘hacking activerecord’s automatic timestamps’, though.

Crap. Can’t you just do this for me?

This is easy, I swear. Like I said, it’s really already been done, so you don’t have to do any revolutionary hacking of any sort. In fact, you just need to change a few characters on one line of one file in ActiveRecord’s Timestamp class, just like they did in the actual patch to Railsa.

Where is this timestamp crap?

In your Rails app’s root directory, open up ‘vendor/rails/activerecord/lib/active_record/timestamp.rb’ file. (You did already freeze your Rails application, right?) Find the following line:

base.cattr\_accessor :record\_timestamps, :instance\_writer =\> false

The part we are interested in changing is ‘cattr_accessor’. We want to make it class inheritable, and ‘cattr_accessor’ does not allow such behavior, as Dr. Nic pointed out, once upon a time. Luckily, ActiveSupport provides ‘class_inheritable_accessor’. So, change the above line to the following:

base.class\_inheritable\_accessor :record\_timestamps, :instance\_writer =\> false

Uh, what now?

Good. Now, I created a class method in a model that should be used as a block to turn off timestamps for any table updates within.

class SuperBowlLosers \< ActiveRecord::Base   def skip\_stampings     self.record\_timestamps = false     yield     self.record\_timestamps = true   end end

Now, elsewhere, I can make a minor update to a field without updating the ‘updated_at’ portion.

  \# Should probably be done every few minutes   @pats = SuperBowlLosers.find\_by\_year(2008)   SuperBowlLosers.skip\_stampings do     @pats.update\_attribute(:pissing\_and\_moaning\_and\_crying\_at, Time.now)   end

TA DA!

See? That wasn’t so bad, was it? For methods other than my ‘skip_stampings’ method (that I did not dream up myself, as you’ll see), check out Evan Weaver’s ‘hacking activerecord’s automatic timestamps’.