Creating a profile with after_create

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?

On Jan 28, 2008, at 11:48 AM, Peter wrote:

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.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

thanks, this seems to be working

def create_profile
(self.profile = Profile.new).save!
end

although i have the feeling this could be written in a cleaner way…?

On Jan 28, 5:54 pm, Rob B. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs