Whenever a User object is created, I want a UserInfo object to be created too, and linked to it.
Unfortunately this does not create any UserInfo:
class User < ActiveRecord::Base
has_one :user_info
...
def init
self.user_info = user_info
self.save!
end
Why is the init method not called? How to reach my goal?
sombe’s technique is right, but his details aren’t ideal. In fact, since
create_user_infois already a method onUserinstances, all you want is something like:Edit:
initdoesn’t do anything particularly magical under Rails (I… don’t think it does under basic Ruby either – are you thinking ofinitialize? I’ll assume you are).initializeis fired off when an instance of the Ruby class is created in memory. That’s divorced by quite some margin from an instance of the model being created in the database; a new class instance could be due to you callingbuild(and not saving yet), or even due to reading an instance out of the database.If you want to step in on database operations, you need to make use of the ActiveRecord callbacks. You might find my answer to this question useful.