Before_create in the rail model

I have a rail model Userthat has fields name, emailand hash.

I save the data in this:

@u = User.create(:name=>'test', :email=>"test@mail.com")
@u.save

How can I enable the callback before_createso that the hash value gets the hash string by the following code before saving the record:

Digest::SHA1.hexdigest('something secret' + email)

What will my model look like User?

class Employee < ActiveRecord::Base
   before_create :set_hash

   def set_hash 
      //what goes in here?
   end
end
+5
source share
1 answer

You can access (and change) instance variables of your current model using the self keyword.

def set_hash
  self.email = Digest::SHA1.hexdigest('something secret' + self.email)
end
+8
source

All Articles