Disabling Timestamps by Model in Rails 1.2.x

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'.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.

Powered by Drupal - Original Theme by Artinet - Theme Enhancements by Me