Friday, March 21, 2008

How to setup updated_at field manually

There's a simple case. Say I've got a model which logic depends on the magic updated_at field and I would like to test it. But the question is how to set the value manually up, when you need it? If you try something like

@article.update_attributes :updated_at => 10.minutes.ago

Then you'll have your updated_at field set to Time.now whatever you pass in it, because ActiveRecord will overwrite it by default.

The answer is simple, use the 'record_timestamps=' class-method which switches on/off the automatic updating of the created and updated fields.

Article.record_timestamps = false
@article.update_attributes :updated_at => 10.minutes.ago
Article.record_timestamps = true

That's it.

1 comment:

Diego said...

Thanks! I was trying to update this field on my functional test and your post saved my day.