Participating in the monitoring Process
Participate in the monitoring process
ActiveRecord controls the life cycle of the model object, creates them, monitors them as they are modified, saved, and updated, and monitors them when they are deleted. Using the callback function, ActiveRecord allows our code to participate in this monitoring process.
ActiveRecord defines 20 callback functions in total. 18 pairs of before and after, with two exceptions: After_find and After_initialize.
There are two ways of implementing callback.
First, write code directly in the object's callback method.
Class Order
< ActiveRecord::Base
def after_save
Self.payment_due | | = Time.now + 30.days
End
Second, declaring a processor for a callback, the processor can be a method, or a block.
Class Order < ActiveRecord::Base
Before_validation:normalize_credit_card_number
after_create do |order|
Logger.info ' order #{order.id} created '
end
protected
def normalize_credit_card_number
self.cc _number.gsub! (/[-\s]/, "")
End End
You can specify multiple handlers for a callback function, and multiple handlers are executed in the order specified, unless one of the handlers returns false, which terminates the subsequent handler.
Because you need to optimize performance, define After_find and After_initialize only in a method, and if you use other methods, the defined handlers are ignored.
Grouping Related Callbacks together
Callback Group
The related callback processing methods can be defined in separate classes so that they can be shared in multiple model. A processing class is to define callback methods in a class and put them in the App/models folder.
Class Creditcardcallbacks
def before_validation (model)
model.cc_number.gsub! ( /[-\s]/, ') End
-
class Order < activerecord::base
Before_validation creditcardcallbacks.new
End
Class Subscription < activerecord::base
before_validation creditcardcallbacks.new
End
The before_validation of the creditcardcallbacks above is shared, which requires that both order and subscription contain cc_number attributes. Shared handlers, which need to handle the same properties, certainly need to share the handler's model with the same name as the property.