Duncan's got the correct answer in terms of using your factory as a callback. But it might help you to understand what was going wrong.
Class methods receive the class as self, instance methods receive the instance as self. When you provide any method a block, the scope of the calling method is used for the block.
after_create is a class method that adds a call back to the block provided or methods listed as arguments. Blocks provided to callbacks (after_create, before_save, etc) are interpreted in the context of class methods. So self refers not, to the object being created, but the Class of the object being created.
In this snippet:
after_create {self.profile = ProfileFactory.create_profile(self.role)}
self is the User class, not an instance of the User class as you expect.
Compared to the more traditional after_create syntax that Matt was hinting at, where an instance method is added to the callback chain. In this context self refers to the instance.
class User < ActiveRecord::Base
has_one :profile
after_create :add_profile
protected
def add_profile
self.profile = ProfileFactory.create_profile(role)
end
end
EmFi, This makes a lot of sense. So
just to clarify, when invoking methods
that are in the class from the
callback methods but NOT actually in
one of the callback methods, allows us
to get around this class method
problem, and use the current instance?
Yes, but not for the reasons you think. Callbacks only looks for instance methods when passed a symbol.
Instead what you've found a way to get around the instance method problem. You can't give a callback a class method, but you can provide it a block in which it calls one. I guess you could also define an instance method that calls the class method, but that seems a little backwards.