17 août 2009

attr_accessor and timestamps

I had an attribute set with attr_accessor. Then in a before_update, I would set an actual DB field on certain conditions like so:


def before_update
if ....
self.my_db_field = self.my_attribute_from_attr_accessor
end


The problem I encountered is that, if the attribute in attr_accessor is the only one that is modified, the updated_at timestamp is not changed...

If you look at the lifecycle of an ActiveRecord update, I think the timestamp update occurs some time BEFORE the before_update...

Too bad! A simple workaround, though, is to put the code above in the validation, as this definitely gets executed before the timestamp update.

Aucun commentaire:

Enregistrer un commentaire