18

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

Zabba
  • 64,285
  • 47
  • 179
  • 207
  • 3
    I'm using after_initialize for example for builings associations. An example after_initialize :build_text, :unless => :text. Very helpful when using accepts_nested_attributes_for – Dmitry Polushkin Feb 05 '11 at 18:21
  • Here is an updated link [for the Rails 4 guide on after_initialize](http://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find) – stereoscott Jul 28 '13 at 23:57

1 Answers1

10

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

curv
  • 3,796
  • 4
  • 33
  • 48