I want to create a hash that combines the creating user’s user_id + the record’s ID to make a MD5 hash, but only on record creation. (Reasons are long-winded but this extracts it).
I am trying:
class BlogPost < ActiveRecord::Base
after_create :hash_this
private
def hash_this
self.info_md5_hashed = (id.to_str + creator_user_id).my_MD5_hash_method
end
end
How can I make sure that the info_md5_hashed field actually gets saved to the database?
If I use before_create I would assume that the ID is not yet available? 🙁
If I use after_create I would assume that the ID is now available
– but do I need to do another save somehow to store the newly calculated info_md5_hashed field value?
Yes, you will have to save the record twice, since ID generation happens in the database. The only way around that is to pre-sequence an ID, but there’s almost certainly no point and you should just accept that you will have to save the record twice 😉
Just call the second save from inside your
after_createhook- it’s ok to do this (i.e. will not be a looping recurrence issue) because the second save won’t re-trigger that hook again 😉n.b. You could always base the hash on something you know to be unique, such as the username or email, if you want to avoid a double-save.