Saturday, July 28, 2007

Turning off Activerecord timestamp

Context: I was trying to increment an article’s views column every time when a reader has viewed the article.

Problem: Whenever I increment the article.views, article.updated_at will be updated by the rails through magic column. That’s not what I want, since updated_at should mean it was last updated by the author of the article, not the reader?!

I could stay with the new meaning of the updated_at, really last_viewed_at, but being a little stubborn, I decided to try out my luck on google.

Ref 1: hacking activerecord’s automatic timestamps

A lot of good stuff, but a lot of errors, too… didn’t work for me.

Ref 2: Turning off Magic Columns

Ahh… But it’s not so thread safe, is it? ;-) The good thing that I learned from Ref 1.

Ref 3: Database Conventions

A lot of good info, but doesn’t totally solve my problem. At least I know that meta class is very useful in this threading scenario. ;-)

Ref 4: Seeing Metaclasses Clearly

Aha… That’s really tricky ;-)

Ref 5: So how do I use remove_method?

Ref 6: This one is coming from me ;-)
  def increment_views
class << self
def record_timestamps; false; end
end

self.increment! :views

class << self
remove_method :record_timestamps
end
end