Patrick
Patrick

Reputation: 475

before_create in rails model

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

Upvotes: 7

Views: 17205

Answers (1)

Zachary Wright
Zachary Wright

Reputation: 24070

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

Upvotes: 9

Related Questions