views:

64

answers:

1

If I have two models that are guaranteed to have a one-to-one correspondence, i.e. if one is created, I will always also need the other, and if one is deleted, I will also want to get rid of the other, what's the best way to tie them together?

I see that the has_one/belongs_to :dependent method takes care of the deletions, but I don't see any similar method to take care of creation.

There seem to be a lot of options on where I could stick in the creation of the submodel, what's the best approach for this?

+3  A: 

You can create the related object manually using before_create callback:

class Person < ActiveRecord::Base
  before_create :create_address
  validates_presence_of :address

  private
  def create_address
    address = Address.new
  end
end
Dmytrii Nagirniak
You may also want to add validation to verify that address is not nil.
Randy Simon
Good point. Added that.
Dmytrii Nagirniak
You probably want to change that to a `before_create` otherwise the validation will fail
Jimmy Stenke
@Jimmy, true. Thanks. Changed.
Dmytrii Nagirniak
Actually, with this approach, I think we'd need to use before_validation_on_create, otherwise validation will happen too early and mess things up.
WIlliam Jones