开发者

Ruby on Rails: Best way to tie together two models that correspond one to one

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 lo开发者_开发技巧t of options on where I could stick in the creation of the submodel, what's the best approach for this?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜