Tuesday, September 16, 2008

Using before_save in the model

I was doing some refactoring of our email subscription functionality and I added a table column to include a hash of the email address which I would use in the unsubscribe process.

So I created a new migration that added the column and calculated the hashes for the existing email addresses in the table, however, it was not automatically creating the hashes using the current functionality.

So, it's a pretty simple call in the model, a function called before_save.

My model file ends up looking like this, which creates the hash right before it saves the email address when someone subscribes.
before_save :add_email_hash

def add_email_hash
self.email_hash = Digest::SHA1.hexdigest(self.email + "addsometexttomakeithardtorecreate")
end

And that's it! An addition to the model file which is supposed to handle this sort of thing, rather than the controller.

No comments: