Active Record回调

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值