开发者

How to use 'after_initialize' in Rails 3?

开发者 https://www.devze.com 2023-02-08 12:25 出处:网络
UPDATE 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 th

UPDATE

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".

Macro-style call to after_initialize is the way to go.



Should after_initialize be used as method or macro-style call ?

This works, but gives a deprecation warning:

def after_initialize
  logger.info "Called after_initialize"
end

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

But the Active Record Validations and Callbacks Guide in 10.4 after_initialize and after_find says:

...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开发者_JAVA技巧 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?

(I guess the guide is wrong, 'cos code is king :D)


Another Update


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.


The call backs should be used as macro style in your model: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

0

精彩评论

暂无评论...
验证码 换一张
取 消