0

这一定是一个普遍的问题,所以我很惊讶谷歌没有找到更多的答案。我正在开发一个具有多种不同实体的 Rails 应用程序,这些实体需要与不同实体的关系。例如:

  1. Address:存储街道地址详细信息的模型(这是我的共享实体)
  2. PersonContact:包括家庭电话、手机和电子邮件地址等内容的模型。这个模型需要有一个与之关联的地址
  3. DogContact: 显然,如果你想接触一只狗,你必须去它居住的地方。

所以,PersonContact并且DogContact应该有外键Address。即使,尽管它们确实是Address. 这很好,除了accepts_nested_attributes_for指望外键Address正常工作。

将外键保留在 中Address但拥有PersonContactDogContact成为拥有对象的正确策略是什么?

4

1 回答 1

0

我相信你应该使用多态关联

为此,您需要在桌子上添加一个addressable_id和一个。您的模型应如下所示:addressable_typeaddresses

class Address < ActiveRecord::Base
   belongs_to :addressable, :polymorphic => true    
end 

class PersonContact < ActiveRecord::Base 
   has_one :address, :as => :addressable
end

class DogContact < ActiveRecord::Base 
   has_one :address, :as => :addressable
end
于 2010-06-14T12:16:46.297 回答