开发者

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

开发者 https://www.devze.com 2022-12-22 16:14 出处:网络
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

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

精彩评论

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

关注公众号