ActiveRecord提供了一些方法,可以讓你對模型生命週期某些階段感興趣時,註冊相對應的回呼方法。例如想在儲存使用者資訊之前,將名稱一律轉為小寫:
class User < ActiveRecord::Base
before_save :ensure_name_downcase
def ensure_name_downcase
name.downcase!
end
end
> ActiveRecord::Callbacks::CALLBACKS
=> [:after_initialize, :after_find, :after_touch, :before_validation, :after_validation, :before_save, :around_save, :after_save, :before_create, :around_create, :after_create, :before_update, :around_update, :after_update, :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback]
=> [:after_initialize, :after_find, :after_touch, :before_validation, :after_validation, :before_save, :around_save, :after_save, :before_create, :around_create, :after_create, :before_update, :around_update, :after_update, :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback]
註冊回呼的方式共有四種,除了以下介紹的之外,還可以接受字串、物件與程式區塊。例如接受一個可評估的字串:
class User < ActiveRecord::Base
before_save 'name.downcase!'
end
before_save 'name.downcase!'
end