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
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.
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/…
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With