Rails 中的多列主键
我正在尝试将桌面应用程序迁移到rails(还处理相当老式的现有数据库)。问题是我在一列中没有唯一的 ID,但表的三列保证了记录的唯一性。
鉴于我有三个表:
authors
author_name,
author_letter,
author_nr1,
author_nr2
...
titles
titel_nr,
titel_name,
...
author_titles
titel_nr,
author_letter,
author_nr1,
author_nr2
作者的“主键”由author_letter、author_nr1、author_nr2组成。
那么我是否需要在这里使用多列主键才能使 Rails 关联正常工作?或者我在这里走错了方向?
I'm trying to migrate a desktop application to rails (also dealing with quite old fashioned existing database). The problem is that I don't have a unique ID in one column, but it's three columns of a table that guarantee uniqueness of a record.
Given I have three tables:
authors
author_name,
author_letter,
author_nr1,
author_nr2
...
titles
titel_nr,
titel_name,
...
author_titles
titel_nr,
author_letter,
author_nr1,
author_nr2
The "primary key" of authors consists of author_letter, author_nr1, author_nr2 here.
So do I need sort of a multicolumn primary key here to have rails associations working? Or am I going in the wrong direction here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不。主键是(像 Rails 默认的那样)记录的 ID。
此外,您可以设置唯一的键,例如
“This”,以保护您的数据库。为了捕捉 Rails 中的独特性,您需要在模型中写入:
No. The Primary Key is (like rails default) the ID of the Record.
In addition you can set unique Keys like
This potects your database. To catch the uniqueness in Rails you need to write into your model:
存在一个名为 composite_primary_keys 的 gem,它允许使用多个列构建主键。
所以,是的,您可以使用多列主键。
但是,如果您能够更改数据模型(情况并非总是如此),我建议向每个表添加一个列 ID,因为这将使您的生活更轻松(并且性能也更高)。
[编辑]
您的composite_primary_keys 类定义将如下所示
希望这会有所帮助。
There exists a gem called composite_primary_keys that will allow to build a primary key using multiple columns.
So, yes, you can use multicolumn primary key.
But, if you are able to change the datamodel (which is not always the case), I would propose to add a column ID to each table, as this will make your life easier (and is also much more performant).
[EDIT]
Your class definition with composite_primary_keys will look like this
Hope this helps.
正如许多人所说:“如果你对抗 Rails,它就会反击”。
真的尽量避免这种情况,如果你没有干净的数据模型,那么 Rails 会很痛苦。
As many people said: "if you fight Rails, it'll strike back".
Really try to avoid such situations, It's pain with rails, if you don't have a clean datamodel.