ruby-on-rails - after_initialize和after_find回调顺序在Active Record对象生命周期中?

标签 ruby-on-rails activerecord callback

来自Rails指南。回调可能会涉及Active Record Object的生命周期。按照执行顺序,它们是(从Rails Guides复制):

创建一个对象


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


我想知道after_initializeafter_find放在哪里?我认为after_initialize应该放在before_validation之前,并且after_find不属于它们中的任何三个。我对么?谢谢。

最佳答案

after_initializeafter_find回调是两个特殊的回调。

定义after_findafter_initialize事件的回调的唯一方法是将它们定义为methods。如果您尝试将它们声明为handlers,它们将被忽略。

API


分别触发after_findafter_initialize回调
由查找器发现并实例化的对象,具有
实例化新对象后触发after_initialize
也一样


Guides


每当激活时,将调用after_initialize回调
通过直接使用new或在
记录是从数据库中加载的。避免需要很有用
直接覆盖您的Active Record初始化方法。

每当Active Record加载时,都会调用after_find回调
数据库中的记录。 after_find在之前被调用
after_initialize(如果已定义)。

after_initializeafter_find回调没有before_ *
对应,但可以像其他Active一样注册
记录回调。

class User < ActiveRecord::Base
  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>



after_initializeafter_find放在AR对象生命周期的何处?

由于它们与所有其他回调不同,并且它们也没有before_ *对应对象,因此作者(这里是指Guides作者)可能有兴趣将它们分开,因为它们是特例。

最后,我同意将after_initialize放在before_validation之前。可能是这样。

关于ruby-on-rails - after_initialize和after_find回调顺序在Active Record对象生命周期中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124018/

相关文章:

ruby-on-rails - rake 中止! ActiveRecord::StatementInvalid: SQLite3::SQLException: 没有这样的表:无法让 Rake Automation 工作

ruby-on-rails - ActiveRecord destroy_all 抛出 StatementInvalid

javascript - 条码扫描仪Phonegap插件;无法将结果保存到全局变量或保存到隐藏字段

Javascript 异步回调 hell

来自 c dll 的 c# 回调,指向 c# 类的指针 arg

ruby-on-rails - 如何使用 Test/Unit, MiniTest 在自动测试中获得颜色输出?

ruby-on-rails - 根据request.xhr设置布局?

mysql - 在 Rails/Heroku 上摄取巨大的 CSV : MySQL Connection Closed - SignalException: SIGTERM

php - 用于网络社交网络的 Ruby on Rails、PHP 或 C++

ruby-on-rails - rails 找到帖子的 user_id = user 的所有评论