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=>"[email protected]")
@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
1
  • 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. Commented Sep 1, 2012 at 0:06

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.