Rails活动记录模型关系——一个模型属于三个模型
我遇到过一个模型需要有三个外国 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为你的设计很糟糕。对于如何实现这一点可能没有太多选择,但您应该考虑如何使用它。就我个人而言,我不会将该模型称为 Detail,因为它不会告诉您有关该模型到底是什么的任何信息。像HardwareConfiguration这样的东西更明确。也许太长了,但您可以根据您的喜好将其缩短为 HardwareConfig 或 Configuration。
该模型应该有一个 id 和三个外键。您还应该向每个外键字段添加数据库索引。
然后每个硬件模型都会有_many :details like:
您可以通过其 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.
Then each hardware model would have_many :details like:
You could look up the detail combo by its ID, or any combination of foreign keys.