7

I have a rails model User that has name, email and hash fields.

I save data to this by doing:

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

How can I incorporate the before_create callback so that before saving the record the hash value gets a hash string by following code:

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

How will my User model look like?

class Employee < ActiveRecord::Base
   before_create :set_hash

   def set_hash 
      //what goes in here?
   end
end
Patrick
  • 475
  • 2
  • 6
  • 16
  • 4
    Incidentally, User.create saves the user, so @u.save is unnecessary. If you want to do something between making a new model and saving, use User.new with the same parameters. – Troy Sep 01 '12 at 00:06

1 Answers1

9

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

def set_hash
  self.email = Digest::SHA1.hexdigest('something secret' + self.email)
end
Zachary Wright
  • 23,480
  • 10
  • 42
  • 56