Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after_initialize & after_find callbacks order in Active Record object life cycle?

From the Rails Guides. Callbacks could hook into Active Record Object's life cycle. In the order of execution, they're (copied from Rails Guides):

Creating an Object

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create
  • around_create
  • after_create
  • after_save
  • after_commit/after_rollback

Updating an Object

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_update
  • around_update
  • after_update
  • after_save
  • after_commit/after_rollback

Destroying an Object

  • before_destroy
  • around_destroy
  • after_destroy
  • after_commit/after_rollback

I am wondering where to put the after_initialize and after_find into above? I think after_initialize should put before before_validation and after_find does not belongs to any three of them. Am I correct? Thanks.

like image 246
Juanito Fatas Avatar asked Apr 17 '14 03:04

Juanito Fatas


1 Answers

The after_initialize and after_find callbacks are the two special callbacks.

The only way to define callbacks for the after_find and after_initialize events is to define them as methods. If you try declaring them as handlers,they’ll be silently ignored.

From the API

after_find and after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well.

From the Guides

The after_initialize callback will be called whenever an Active Record object is instantiated, either by directly using new or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize method.

The after_find callback will be called whenever Active Record loads a record from the database. after_find is called before after_initialize if both are defined.

The after_initialize and after_find callbacks have no before_* counterparts, but they can be registered just like the other Active Record callbacks.

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>

where to put the after_initialize and after_find in the AR object life cycle?

Since they are different from all other callbacks and also they don't have before_* counterparts,so the author(referring to Guides author here) might be interested in putting them separately as they are special case.

And finally I would agree with in putting after_initialize before before_validation. It might be the case.

like image 105
Pavan Avatar answered Sep 23 '22 13:09

Pavan