如果使用连接表,关系是否必须是 HABTM?
我在 Rails 2.x 中有 Worker、Manager 和 Title 模型。还有一个 JOIN 表,其中只有worker_id、manager_id 和title_id(没有明确的模型)。由于这个 JOIN 表(并且没有它的模型),我假设我必须具有以下内容:
在 Worker 模型中,我有:
Worker
has_and_belongs_to_many :managers
has_and_belongs_to_many :titles
但是,实际上,关系是 Worker 只能有 1 个 Manager,但有很多标题。此外,许多 Worker 都有同一个 Manager。
一些示例数据来说明这种关系:
Worker | Title | Manager
Tom | A | M1
Tom | B | M1
Bob | A | M2
Pam | C | M1
上面的 Worker 模型“正确”吗?当创建一个新的 Worker (及其所有关系)时,我会这样做:
worker = Worker.new("A")
title = "B"
manager = "C"
worker.titles << title
worker.managers << manager
worker.save
当我这样做时,我会在数据库中得到以下内容:
Worker | Title | Manager
A | B | null
A | null | C
我想得到:
Worker | Title | Manager
A | B | C
I have Worker, Manager, and Title models in Rails 2.x. There is also a JOIN table that has only worker_id, manager_id, and title_id (no explicit model for this). Because of this JOIN table (and not having a model for it), I assume I have to have the following:
In the Worker model, I have:
Worker
has_and_belongs_to_many :managers
has_and_belongs_to_many :titles
But, in reality, the relationship is that Worker can only have 1 Manager, but many Titles. Also, many Workers have the same Manager.
Some sample data to illustrate the relationship:
Worker | Title | Manager
Tom | A | M1
Tom | B | M1
Bob | A | M2
Pam | C | M1
Is the above Worker model "correct"? When creating a new Worker (and all their relationships), I do:
worker = Worker.new("A")
title = "B"
manager = "C"
worker.titles << title
worker.managers << manager
worker.save
When I do this, I get the following in my database:
Worker | Title | Manager
A | B | null
A | null | C
I would like to get:
Worker | Title | Manager
A | B | C
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以移动 manager_id(因为 Worker 只能在 Manager 上拥有)并具有如下所示的关系
然后,在 Worker 中属于 Manager。
之间的关系:
您需要有一个连接表,例如“workers_titles”,用于保存工人和头衔模型
You can move the manager_id (since, a Worker can have only on Manager) and have the relationships like this
Then, in the Worker belongs_to a Manager.
You need to have a join table, like "workers_titles" for hold the relationships between workers and titles
Models: