Creating has_one models on save


#1

What is the best practice to create has_one (always exist) model
relationships when creating the parent model.

eg:
class User < ActiveRecord::Base
has_one :balance
end

class Balance < ActiveRecord::Base
belongs_to :user
end

A User always has a Balance

I would like to create the Balance model when the User is saved.

There is 3 (maybe more choices to accomplish this), which one is the
best practice:

  1. Create the Balance model and associate it to the User from the
    controller that is creating the User model.

  2. Do it in the User model with after_create :create_balance

  3. Do it in a UserObeserver:

class UserObserver < ActiveRecord::Observer
def after_create(user)
balance = Balance.new(:amount => 0)
balance = customer
balance.save
end
end

Thanks! If this has been covered before, sorry, but just not finding
the right search terms to limit results.


#2

On Tue, Mar 31, 2009 at 6:48 PM, Albert W. <
removed_email_address@domain.invalid> wrote:

belongs_to :user
controller that is creating the User model.
end
end

Thanks! If this has been covered before, sorry, but just not finding
the right search terms to limit results.

Albert, you should be able to do the following:

class User < ActiveRecord::Base

after_save :create_balance

protected

def create_balance

 balance = Balance.new( :amount => 0 )

# fill in any additional attributes

balance.save!

self.balance = balance # associate the balance to the user

end

end

BTW, you can use an after_save filter to invoke the create_balance
method
when you save the

user instance.

Good luck,

-Conrad


#3

Thanks Conrad…

I think after_create is the better filter to use, otherwise the Balance
is reset to 0 everytime there is an update to the User.


#4

Albert W. wrote:

What is the best practice to create has_one (always exist) model
relationships when creating the parent model.

In addition to the technical answers…

Isn’t the relation “always has one” really the relation “is part of”?

Why all the fields are not in the same record?