On Tue, Mar 31, 2009 at 6:48 PM, Albert Wong <
[email protected]> wrote:
>
> 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.
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
>
> --
> Posted via http://www.ruby-forum.com/.
>
> >
>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---