Active Record回调
可用的回调
创建对象时:before_validation, after_validation, before_save, around_save, before_create, around_create, after_create, after_save, after_commit/after_rollback
更新对象时:before_validation, after_validation, before_save, around_save, before_update, around_update, after_update, after_save, after_commit/after_rollback
删除对象时:before_destroy, around_destroy, after_destroy, after_commit/after_rollback
1.after_initialize 和 after_find 回调
当 Active Record 对象被实例化时,不管是通过直接使用 new 方法还是从数据库加载记录,都会调用 after_initialize 回调。使用这个回调可以避免直接覆盖 Active Record 的 initialize 方法。
当 Active Record 从数据库中加载记录时,会调用 after_find 回调。如果同时定义了 after_initialize 和 after_find 回调,会先调用 after_find 回调。
after_initialize 和 after_find 回调没有对应的 before_* 回调,这两个回调的注册方式和其他 Active Record 回调一样。
class User < ApplicationRecord
after_initialize do |user|
puts "You have initialized an object!"
end
after_find do |user|
puts "You have found an object!"
end
end
>> User.new
You have initialized an object!
=> #<User id: nil>
>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
2.after_touch 回调
当我们在 Active Record 对象上调用 touch 方法时,会调用 after_touch 回调。
class User < ApplicationRecord
after_touch do |user|
puts "You have touched an object"
end
end
>> u = User.create(name: 'Kuldeep')
=> #<User id: 1, name: "Kuldeep", created_at: "2013-11-25 12:17:49", updated_at: "2013-11-25 12:17:49">
>> u.touch
You have touched an object
=> true
3.调用回调
下面这些方法会触发回调:create, create!, decrement!, destroy, destroy!, destroy_all, increment!, save, save!, save(validate: false), toggle!, update_attribute, update, update!, valid?
下面这些查找方法会触发 after_find 回调:all ,first, find, find_by, find_by_, find_by_!, find_by_sql, last
使用下面这些方法可以跳过回调:decrement, decrement_counter, delete, delete_all, increment, increment_counter, toggle, touch, update_column, update_columns, update_all, update_counters