Rails 嵌套属性、共享或通用对象的关系
这一定是一个常见问题,所以我很惊讶谷歌没有找到更多答案。我正在开发一个 Rails 应用程序,它有几种不同类型的实体,这些实体需要与不同实体的关系。例如:
Address
:一个存储街道地址详细信息的模型(这是我的共享实体)PersonContact
:一个模型,其中包括家庭电话、手机和电话等信息电子邮件。这个模型需要有一个与之关联的地址DogContact
:显然,如果你想联系一只狗,你就必须去它居住的地方。
因此,PersonContact
和 DogContact
应该具有 Address
的外键。即使它们实际上是 Address
的“拥有”对象。这没什么问题,只是 accepts_nested_attributes_for
依赖于 Address
中的外键才能正常工作。
将外键保留在 Address
中,但让 PersonContact
和 DogContact
成为拥有对象的正确策略是什么?
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:
Address
: a Model that stores the details of a street address (this is my shared entity)PersonContact
: a Model that includes things like home phone, cell phone and email address. This model needs to have an address associated with itDogContact
: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您应该使用多态关联。
为此,您需要在
addresses
表中添加addressable_id
和addressable_type
。你的模型应该看起来像:I believe you should use a polymorphic association.
For that you'll need to add an
addressable_id
and anaddressable_type
on youraddresses
table. And your models should look like: