Rails 如何得出新模型/记录的 ID?
activerecord 如何为新创建的记录分配 ID? ID 值似乎无处不在。有时它们是连续的,但有时它们似乎是某种散列。 有没有办法控制行为?
How does activerecord assign an ID to a newly created record? The ID values seem to be all over the place. Sometimes they are sequential, but sometimes they seem to be some kind of a hash.
Is there a way to control the behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在关系数据库中,您会发现 ID 通常是连续的。在 Rails 的这些数据库中,默认情况下,这恰好是一个自动递增的字段,称为 id 。这是 99% 的情况,这意味着 99% 的情况下您都可以看到这种方式完成。这是理智的方式。
然而,在某些情况下,数据库中的“id”字段可能不会自动递增,而可能是一个字符串。在我目前使用的数据库中,id 字段称为
client_id
,是一个 6 个字符的字符串,例如“RAB001”,需要由代码本身手动分配。这是由于我们支持的旧系统造成的,我们无法修复该问题。就是这样。在其他数据库(例如 Mongoid)中,ID 再次自动生成。但这里有一个区别:它们不是自动递增的数字,而是哈希值。在我碰巧手头的 Mongo 数据库中,对象的
_id
字段之一(注意下划线)是这个可爱的、易于理解的1 哈希:4e22b5812f8b7d6f6d000001。这是由 Mongo 自动生成的,我并不关心它是什么,除非我需要查找一个对象并且没有其他方法可以通过另一个唯一值查找它。
我建议坚持使用自动生成 ID 系统,无论是传统数据库系统(例如 PostgreSQL 或 MySQL)还是 Mongo 提供的系统。
任何需要手动生成记录主键的系统都需要有一个巨大的“HERE BE DRAGONS”标签,并且应该像处理硝酸甘油或与这个恰当的类比类似。 如果可以的话请避免使用这个系统。
1 我在这里是在讽刺。
Within a relational database you'll see that IDs are usually sequential. This happens to be an automatically incrementing field called
id
by default in these databases with Rails. This is the 99% case, meaning that 99% of the time you can expect to see it done this way. It's the sane way.However, There are some cases in which the "id" field within the database may not be automatically incrementing and may instead be a string. In a database I am working with at the moment, the id field is called
client_id
, is a 6-character string such as "RAB001" and needs to be manually assigned by the code itself. This is due to a legacy system we are supporting and there's nothing we can do to fix that. It's just how it is.In other databases such as Mongoid the ids are, once again, generated automatically. There's a difference here though: instead of them being automatically incrementing numbers they are a hash. In a Mongo database I happen to have handy, one of the object's
_id
fields (note the underscore) is this lovely, easy-to-understand1 hash:4e22b5812f8b7d6f6d000001
. This is automatically generated by Mongo and I don't really care what it is except for when I need to find an object and there's no other way of finding it by another unique value.I would recommend sticking with an automatically generating ID system, be it something provided by the traditional database systems such as PostgreSQL or MySQL or something by Mongo.
Any system where you need to generate the primary key for a record manually needs to have a huge "HERE BE DRAGONS" label on it and should be handled like a case of nitroglycerin or similarly to this apt analogy. Avoid this system if you can.
1 I am being sarcastic here.