Forum: Ruby on Rails Creating has_one models on save

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Francis W. (Guest)
on 2009-04-01 05:48
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.
Conrad T. (Guest)
on 2009-04-01 06:44
(Received via mailing list)
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
Francis W. (Guest)
on 2009-04-01 09:48
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.
Phlip (Guest)
on 2009-04-01 16:48
(Received via mailing list)
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?
This topic is locked and can not be replied to.