Rails:这些模型的正确关联是什么?
这个问题的正确关联是什么?
共有三种模型:
- 居民
- 方
- 地址
每个居民
和方
都有一个地址
每个地址
可以属于一个< code>Resident 或 Party
或两者。
同一地址
可以有多个参与方
,并且该位置可以有多个居民
居住。
habtm 关系是这些模型的最佳解决方案吗?
我考虑过进行多态关联,但出现了冲突,因为地址
可能同时属于Resident
和Party
多个有时
我希望能够做一些事情,例如...
address = Address.find_or_create_by_street("100 Some Street")
# Associate the Party with a specific Address:
party_object.address = address
# Find all Parties happening at a specific Address:
address.parties do ...
# Find all Residents located at a specific Address:
address.residents.each do ...
运行 Rails 3 + MySQL 5.5
What is the correct association for this problem?
There are three models:
- Residents
- Parties
- Addresses
Each Resident
and Party
has an Address
Each Address
can belong to a Resident
or Party
or to both.
There can be multiple Parties
at the same Address
and multiple Residents
living at that location.
Is a habtm relationship the best solution for these models?
I looked into doing polymorphic associations but a conflict arises because an Address
might belong to both Resident
and to Party
mulitple times
I would like to be able to do things like...
address = Address.find_or_create_by_street("100 Some Street")
# Associate the Party with a specific Address:
party_object.address = address
# Find all Parties happening at a specific Address:
address.parties do ...
# Find all Residents located at a specific Address:
address.residents.each do ...
Running Rails 3 + MySQL 5.5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为不需要多态性
I don't see a need for Polymorphism
Rails 专家似乎正在逐步停止使用 habtm。我认为你可以用一个简单的 has_many 来做到这一点:
从这些关联中,你可以做类似
Schema
的事情SQL 模式(省略 Rails 默认值)将与此一起使用,看起来像:
编辑
更新:has_one -> :belongs_to 按照 @klochner 的正确建议,关于居民和当事人。
The Rails gurus seem to be phasing out their use of habtm. I think you can do it with a straightforward has_many:
From those associations you can do things like
Schema
The SQL schema (leaving out the Rails defaults) that would go with this would look something like:
EDIT
Updated :has_one -> :belongs_to on Residents and Parties as correctly advised by @klochner.