0

Possible Duplicate:
Correct Way to Set Default Values in Rails

I have two data tables:

1) User

2) Profile (which has the field user_id)

They are associated through:

  • User has_one Profile
  • Profile belongs_to User

Is there a possibility to save some default values in the profile table each time I create a new user?

Thanks for your help!

Community
  • 1
  • 1
BiallaC
  • 167
  • 1
  • 1
  • 6

2 Answers2

1

You can create default profile by using ActiveRecord callbacks.

Just create a method, and use it as :after_create

class User < ActiveRecord::Base

  has_one :profile

  after_create :create_default_profile

  def create_default_profile
    profile = build_profile
    # set parameters
    profile.save
  end

end

build_profile builds and links an instace of Profile, but doesn't save it. create_profile is the same, but it also saves the object. For the full description, see the ActiveRecord documentation.

You can add attributes to both build_ and create_profile as a hash, so you probably can reduce create_default_profile to one line:

def create_default_profile
  profile = create_profile :some => 'attirbute', :to => 'set'
end
Dutow
  • 5,638
  • 1
  • 30
  • 40
  • I think this could work - but how could I link the new created profile to the user I have just created...I dont' get it. What do I have to fill in the create_default_profile method? – BiallaC Jan 18 '13 at 19:42
  • something in the create_default_profile like profile = Profile.new(user_id:self.id) – Edward Jan 18 '13 at 19:45
  • Yeah, it worked! Thanks a lot! You are awesome! I tried it with "user_id:self_id". – BiallaC Jan 18 '13 at 19:53
  • One last question: Why do I have to use self.id? Why does user.id does not work. – BiallaC Jan 18 '13 at 20:20
0

Yes, you can add default value for profile.

I am setting some values for member_standing and points attributes of profile for a user.

In create action for users controller

def create
  @user = User.new(params[:user])
  profile = @user.profiles.build(:member_standing => "satisfactory", :points => 0)
  if @user.save
    redirect_to @user
  else
    render "new"
  end
end
Jason Kim
  • 18,102
  • 13
  • 66
  • 105
  • mmmh, when I am doing this I get the error message "undefined method `build' for nil:NilClass" for UsersController#create... – BiallaC Jan 18 '13 at 19:23