I have a User and a Profile model, and want to use the last one for
storing some settings and preferences. I think i have the
relationships right (User...has_one :profile,
Profile...belongs_to :user) and a user_id field in the profile_table
What i would like to do is automatically create a profile after
someone registers, using...
after_create :create_profile
...in the User model and in the same file...
def create_profile
profile.create!
end
this doesn't work, and self.profile.create...etc neither. What am i
doing wrong here? Doesn't profile (in profile.create!) refer to the-
created-user.profile?
Here's how this is handled in one of my current applications:
class User < ActiveRecord::Base
has_one :preference, :dependent => :destroy
after_create :initialize_preference
protected
# after create filter
def initialize_preference
(self.preference = Preference.default).save
end
end
class Preference < ActiveRecord::Base
belongs_to :user
def self.default
new(DEFAULTS)
end
end
And the Preference::DEFAULTS is just a hash of attribute values. Preference.default is also used for anonymous users on the system. If you substitute "Profile" for "Preference", I think you'll get the behavior that you're looking for.