如何使用'after_initialize“在Rails 3的? [英] How to use 'after_initialize' in Rails 3?
问题描述
更新
余错误地检查了edgerails导,而不是目前正确导轨3引导件(其具有没有提及after_initialize的)。不知道为什么edgerails指南不正确,但 - ?我以为edgerails导向应该是最新的了最新的指南
I wrongly checked the edgerails guide instead of the currently correct Rails 3 guide (which has no mention of after_initialize). Not sure why the edgerails guide is "incorrect" though - I thought edgerails guide was supposed to be the latest up-to-date guide?
我要离开这个问题的,是以防万一有人来寻找同样的问题。
I'm leaving this question as-is just in case someone comes looking for the same "problem".
宏式调用 after_initialize
是要走的路。
应该 after_initialize
作为方法或宏风格的电话吗?
Should after_initialize
be used as method or macro-style call ?
这工作,但给人以德precation警告:
This works, but gives a deprecation warning:
def after_initialize
logger.info "Called after_initialize"
end
DE preCATION警告:基地#after_initialize已经去precated, 请使用Base.after_initialize:方法来代替
DEPRECATION WARNING: Base#after_initialize has been deprecated, please use Base.after_initialize :method instead.
本作品,并且没有警告:
This works, and there is no warning:
after_initialize :do_this_after_initialize
def do_this_after_initialize
logger.info "Called after_initialize"
end
不过的活动记录验证和回调指南的的<一个href="http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#after_initialize-and-after_find">10.4 after_initialize和after_find 说:
...如果你尝试注册 after_initialize或after_find使用 宏观样式类的方法,他们将 刚刚被忽略。此行为是 出于性能的考虑,因为 after_initialize和after_find会 这两个被调用找到的每个记录 在数据库中,显著减缓 下查询......
...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...
因此,这意味着,宏观式的使用是低效与方法式的方法是什么?
So that means that the macro-style usage is inefficient versus the method-style way?
(我的猜到的导向是错误的,'因为code为王:D)
(I guess the guide is wrong, 'cos code is king :D)
另一个更新
Another Update
href="https://github.com/rails/rails/commit/38d31b0ef0b9c9616918819b5ac5b9d21c539fd7">承诺从2011年1月28日在这里一个高清after_initialize 。
A commit here from January 28, 2011, suggests that the correct way is still to use the macro-style call, not a def after_initialize
.
推荐答案
的回调应作为宏观风格模型:<一href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
The call backs should be used as macro style in your model: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
这篇关于如何使用'after_initialize“在Rails 3的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!