Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 595
Patrick Avatar asked Aug 03 '10 02:08

Patrick


People also ask

What is call back in Rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

What is the difference between delete and destroy in Rails?

Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.

What are .includes in Rails?

Rails provides an ActiveRecord method called :includes which loads associated records in advance and limits the number of SQL queries made to the database. This technique is known as "eager loading" and in many cases will improve performance by a significant amount.


1 Answers

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
like image 87
Zachary Wright Avatar answered Oct 04 '22 10:10

Zachary Wright