如何关闭 Rails Active Record 中的 auto_increment
是否可以在 ActiveRecord 中创建没有 auto_increment
标志的主键?
我不能这样做,
create table :blah, :id => false
因为我想在列上有主键索引。我查找了文档,但没有找到任何有用的东西。
是否可以创建不带auto_increment的主键?
Is it possible to create primary key without auto_increment
flag in ActiveRecord?
I can't do
create table :blah, :id => false
because I want to have primary key index on the column. I looked up documentation but didn't find anything useful.
Is it possible to create primary key without auto_increment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个?
Try this?
好吧,这个问题很旧,OP 没有指定版本。这里给出的答案都不适合我使用这些版本:
我最终选择了这个:
我希望这可以节省有人花时间跟踪这个问题,或者更糟......使用答案而不检查它对数据库的作用...因为使用 sojourner 或 jim 的答案(以及我的依赖项版本)的结果是迁移运行良好,但允许 NULL id,并且允许重复的 id。我没有尝试 Shep 的答案,因为我不喜欢 db/schema.rb 不一致的想法(+1 给 Shep 明确说明这个缺点,有时这是一件坏事)
我不确定其重要性的这个,但使用此解决方案,mysql
describe
将其显示为主键,与具有默认 :id 的 AR 表相同...如:具有 AR 默认 :id
表的表与我的解决方案:
这有点有趣,因为使用我的解决方案迁移生成的 SQL 不包括“主键”(当然)...但是使用 AR 默认值:id 则包含...所以看起来 mysql,至少对于
describe
将非空唯一索引键视为主键HTH 某人
Okay, the question is old and the OP did not specify versions. None of the answers given here worked for me with these versions:
I ended up going for this:
I hope that saves someone out there from spending time tracking this down, or worse ... using the answer without checking what it does to the db ... because the result of using either sojourner's or jim's answers (with my versions of the dependencies) is that the migration runs fine but NULL ids are allowed, and duplicate ids are allowed. I did not try Shep's answer because I don't like the idea of db/schema.rb being inconsistent (+1 to Shep for being explicit about that shortcoming, sometimes that'd be a Bad Thing)
I'm not sure the significance of this, but with this solution, mysql
describe
shows it as a primary key, same as an AR table with default :id ... as in:table with AR default :id
table with my solution:
which is sort of interesting because the SQL generated by the migration with my solution does not include "PRIMARY KEY" (of course) ... but with AR default :id it does ... so it seems mysql, at least for
describe
treats a non-null unique-indexed key as a primary keyHTH someone
这对我不起作用,但以下方法起作用了:
唯一的问题是你在 schema.rb 中丢失了它。
That didn't work for me, but the following did:
Only problem is that you lose it in the schema.rb.
要从 Rails 5 开始禁用自动增量,您可以简单地传递
例如
To disable auto increment as of Rails 5 you can simply pass
for instance
您可以创建一个像这样的表:
这在 Rails 4.0.2 和 Postgresql 9.3.2 中确实有效。
You can create a table like this:
And that really works in Rails 4.0.2 and Postgresql 9.3.2.
注意:从Rails 5.1开始默认主键是bigint。 http://www.mccartie.com/2016/12/05/ Rails-5.1.html
如果你想要 4 字节密钥更改 :bigint 为 :integer
Notice: Since Rails 5.1 default primary keys are bigint. http://www.mccartie.com/2016/12/05/rails-5.1.html
If you want 4-byte key change :bigint to :integer