With Rails there's a useful set of callback methods that can be used within model classes. They include after_create, before_validation and the one I want to talk about after_initialize.
A lot of cool things can be done with after_initialize, especially if one uses the database as a means to store meta-data about a model. Use the after_initialize method to transform your models with Ruby after they're fethced from the database. Consider the following User model definition:
-
class User <ActiveRecord::Base
-
has_many :memberships,
rder => "memberships.group_id, memberships.expires_at desc", :group => "group_id" -
end
It's pretty clear that with the :group => "group_id" that I want a unique set of Membership objects. That works well when I've already got a User and do user.memberships but not at all when I do User.find(:first, :include => :memberships); likely because of the way the join is set up and grouping on that may not be possible.
I still wanted to use eager loading so I thought that it would be an OK sacrifice to fetch all the Membership objects even if I wanted to pare it down after I initialize the User object (with eager loading). I defined:
-
class User <ActiveRecord::Base
-
-
def after_initialize
-
do stuff with @memberships instance varible
-
end
-
end
Except it doesn't work. Quickly I found the following from active_record/base.rb (click link for source): right where it does the after_initialize callback! But it wasn't working for me. I needed to dig further.
Further research indicated that before the creation of the @memberships instance variable that would hold the collection of Membership objects the after_initialize callback was being fired off in the User model. Using after_initialize would not work due to the design of ActiveRecord. I'm still searching for an elegant way to work the way I want. I'll post again when I find it!


Hi Lisa,
Thank you for this insightful post. I just ran into the same issue. I tried to do
def after_initialize
myhasmanyassoc.build
end
It would be great if another callback was provided that fires after the associations are available as well.
- Johannes
Comment by Johannes Fahrenkrug — May 6, 2008 @ 09:25