Rails活动记录模型关系——一个模型属于三个模型

发布于 2024-10-10 16:35:43 字数 299 浏览 1 评论 0原文

我遇到过一个模型需要有三个外国 ID 的情况。该表包含属于三个型号的信息。

例如- 三种型号 - 键盘、鼠标、显示器 现在我有了第四个模型详细信息 - 其中包含有关键盘 1、鼠标 1 和显示器 1 等任意组合会发生什么情况的信息。

那么什么是好的设计模式呢?

现在我使用的是 Detail.find_by_keyboard_id_and_mouse_id_and_monitor_id(keyboard1id, mouse1id, Monitor1id) #=> Detail1

这当然不是最好的方法......

I have situation where a single model needs to have three foreign ids. This table has the information which belongs to three models.

e.g. -
Three models - Keyboard, Mouse, Monitor
Now i have fourth model details - which has information about what will happen for any combination like keyboard1, mouse1 and monitor1.

So what should be good design pattern for this ?

Right now what i use is Detail.find_by_keyboard_id_and_mouse_id_and_monitor_id(keyboard1id, mouse1id, monitor1id) #=> Detail1

Which of course is not a best way to go...

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

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

发布评论

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

评论(1

痕至 2024-10-17 16:35:43

我不认为你的设计很糟糕。对于如何实现这一点可能没有太多选择,但您应该考虑如何使用它。就我个人而言,我不会将该模型称为 Detail,因为它不会告诉您有关该模型到底是什么的任何信息。像HardwareConfiguration这样的东西更明确。也许太长了,但您可以根据您的喜好将其缩短为 HardwareConfig 或 Configuration。

该模型应该有一个 id 和三个外键。您还应该向每个外键字段添加数据库索引。

class Detail < ActiveRecord::Base
  belongs_to :keyboard
  belongs_to :mouse
  belongs_to :monitor
end

然后每个硬件模型都会有_many :details like:

class Keyboard < ActiveRecord::Base
  has_many :details
end

您可以通过其 ID 或外键的任意组合查找详细组合。

Detail.find(id)
Detail.find_all_by_keyboard_id(keyboard_id)

I don't think what you have is a bad design. There probably aren't too many options for how this should be implemented, but you should think about how you want to use it. Personally, I wouldn't call the model Detail since it doesn't tell you anything about what the model really is. Something like HardwareConfiguration is more explicit. Maybe too lengthy, but you could shorten it to HardwareConfig or Configuration, depending on your taste.

This model should have an id and the three foreign keys. You should add database indexes to each foreign key field as well.

class Detail < ActiveRecord::Base
  belongs_to :keyboard
  belongs_to :mouse
  belongs_to :monitor
end

Then each hardware model would have_many :details like:

class Keyboard < ActiveRecord::Base
  has_many :details
end

You could look up the detail combo by its ID, or any combination of foreign keys.

Detail.find(id)
Detail.find_all_by_keyboard_id(keyboard_id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文