Rails 嵌套属性、共享或通用对象的关系

发布于 2024-09-05 12:13:33 字数 625 浏览 6 评论 0原文

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

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

因此,PersonContactDogContact 应该具有 Address 的外键。即使它们实际上是 Address 的“拥有”对象。这没什么问题,只是 accepts_nested_attributes_for 依赖于 Address 中的外键才能正常工作。

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

This has to be a common problem, so I'm surprised that Google didn't turn up more answers. I'm working on a rails app that has several different kinds of entities, those entities by need a relation to a different entity. For example:

  1. Address: a Model that stores the details of a street address (this is my shared entity)
  2. PersonContact: a Model that includes things like home phone, cell phone and email address. This model needs to have an address associated with it
  3. DogContact: Obviously, if you want to contact a dog, you have to go to where it lives.

So, PersonContact and DogContact should have foreign keys to Address. Even, though they are really the "owning" object of Address. This would be fine, except that accepts_nested_attributes_for is counting on the foreign key being in Address to work correctly.

What's the correct strategy to keep the foreign key in Address, but have PersonContact and DogContact be the owning objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

椵侞 2024-09-12 12:13:33

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

为此,您需要在 addresses 表中添加 addressable_idaddressable_type。你的模型应该看起来像:

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

I believe you should use a polymorphic association.

For that you'll need to add an addressable_id and an addressable_type on your addresses table. And your models should look like:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文