Dercni
Dercni

Reputation: 1224

Creating a default value in profile based upon user id

I have created a profile model where customer user attributes will be stored.

I have included the following in my user model which creates the profile record when a new user is created.

before_create :build_profile

Is is possible to set a default value in the profile model based upon the user model?

For example I would like the default profile 'alias' to be set to 'User'+user_id

Upvotes: 0

Views: 124

Answers (1)

Dan Laffan
Dan Laffan

Reputation: 1554

Perhaps you should consider creating a new Profile when you are finished creating a new User, by using a callback.

Callbacks are triggers that you can latch onto in order to get specific tasks done. The general idea is that you would write a private method in your User model to create an associated profile, and then have it triggered just after the User model has completed creating a new user. You could do something like this:

# app/models/user.rb
after_create :create_a_profile

Then in your private methods (further down in the user.rb file):

# app/models/user.rb    

private

def create_a_profile
  Profile.create(user_id: self.id, etc...)
end

This would make your profile_controller simpler - all you need to do is load the profile of the current_user and then allow the user to update the extra details in the normal CRUD?

Upvotes: 1

Related Questions