ruby-on-rails - ActiveRecord:方法名称作为符号传递时,不调用after_initialize

标签 ruby-on-rails activerecord

我注意到当回调符号作为输入传递时,Rails不会触发after_initialize回调。

下面的代码不起作用。

class User < ActiveRecord::Base
  after_initialize :init_data

  def init_data
    puts "In init_data"
  end

end

下面的代码有效。
class User < ActiveRecord::Base

  def after_initialize 
    init_data
  end

  def init_data
    puts "In init_data"
  end
end

有人可以解释这种行为吗?

注意1

ActiveRecord documentation说了有关after_initialize的以下内容:
Unlike all the other callbacks, after_find and after_initialize will 
only be run if an explicit implementation is defined (def after_find). 
In that case, all of the callback types will be called. 

虽然说after_initialize需要显式实现,但是我发现上一段中的第二句话是模棱两可的,即In that case, all of the callback types will be called.什么是all of the call back types

文档中的代码示例包含一个不使用显式实现的示例:
after_initialize EncryptionWrapper.new

最佳答案

根据documentation,您不能对after_initializeafter_find回调使用宏风格的类方法:

The after_initialize and after_find callbacks are a bit different from the others. They have no before_* counterparts, and the only way to register them is by defining them as regular methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.



简而言之,您必须定义一个after_initialize实例方法:
class User < ActiveRecord::Base

  def after_initialize
    do_stuff
  end

end

关于ruby-on-rails - ActiveRecord:方法名称作为符号传递时,不调用after_initialize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3826153/

相关文章:

ruby-on-rails - Rails - 按日期范围过滤

ruby-on-rails - Rails 3 中的 Gemfile 中的组?

ruby-on-rails - 带有 Ruby on Rails 路线的短网址

ruby-on-rails - Group ActiveRecord::Relation By Field Into Hash With Dictionary

ruby-on-rails - 如何在 Rails 中设置模型继承?我有一个类和两个子类

ruby-on-rails - 为什么 rails 在设置后更改属性 _was 值的类型?

ruby-on-rails - 事件管理员更改 csv 的 header 并向输出添加文本

ruby-on-rails - 局部变量、实例变量、全局变量和类变量有什么区别?

ruby-on-rails - 通过 2 个不同的关联模型进行 Rails 查询

ruby - 扩展 ActiveSupport::Notifications.subscribe, instantiation.active_record 钩子(Hook)