如何在Rails Active Record中关闭auto_increment

是否可以在ActiveRecord中创建没有auto_increment标志的主键?

我做不到

 create table :blah, :id => false 

因为我想在列上有主键索引。 我查了一下文档,但没有找到任何有用的东西。

是否可以在没有auto_increment的情况下创建主键?

试试这个?

 create_table(:table_name, :id => false) do |t| t.integer :id, :options => 'PRIMARY KEY' end 

好的,问题是旧的,OP没有指定版本。 这些答案中没有一个对我有用这些版本:

 mysql2 0.3.11 rails 3.2.13 mysql 5.5 

我结束了这个:

 class SomeMigration < ActiveRecord::Migration # emulate a primary_key column without auto-increment # the solution here is to use a non-null integer id column with a unique index # this is semantically different from PRIMARY KEY in mysql but not # _too_ functionally different, the only difference is that mysql enforces # no-more-than-one-primary-key but allows >1 unique index def up create_table :foobars, :id => false do |t| t.integer :id, :null => false t.string :name end add_index :foobars, :id, :unique => true end end 

我希望能够节省一些人花时间跟踪这个问题,或者更糟糕的是…使用答案而不检查它对数据库的作用…因为使用了sojourner或jim的答案的结果(使用我的版本的依赖项) )是迁移运行正常但允许NULL ID,并允许重复的ID。 我没有尝试Shep的答案,因为我不喜欢db / schema.rb不一致的想法(对于明确关于这个缺点的+1来说是Shep,有时候这是一个坏事)

我不确定这个的意义,但是通过这个解决方案,mysql describe它显示为主键,与默认的AR表相同:id …如:

具有AR默认值的表:id

 +---------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | 

表与我的解决方案:

 +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | 

这有点有趣,因为迁移与我的解决方案生成的SQL不包括“PRIMARY KEY”(当然)……但AR默认:id它确实…所以它似乎是mysql,至少对于describe对待非空唯一索引键作为主键

HTH有人

这不适合我,但以下做了:

 create_table(:table_name, :id => false) do |t| t.column :id, 'int(11) PRIMARY KEY' end 

唯一的问题是你在schema.rb中丢失了它。

您可以创建一个这样的表:

 class CreateUsers < ActiveRecord::Migration def change create_table :routers, { id: false } do |t| t.integer :id end execute "ALTER TABLE routers ADD PRIMARY KEY (id);" end end 

这在Rails 4.0.2和Postgresql 9.3.2中确实有效。

要在Rails 5中禁用自动增量,您只需传递即可

 default: nil 

例如

 create_table :table_name, id: :bigint, default: nil do |t| # ... fields ... end 

在Rails 5中,你可以做到

 create_table :blah, id: :integer do |t| 

如果要更改主键列的名称,请传递primary_key参数:

 create_table :blah, id: :integer, primary_key: :my_awesome_id do |t| 

请参见create_table文档 。

  def change create_table :tablename do |t| # t.string :fieldname end change_column :tablename, :id, :bigint, auto_increment: false end 

注意:由于Rails 5.1默认主键是bigint。 http://www.mccartie.com/2016/12/05/rails-5.1.html

如果您想要4字节密钥更改:bigint to:integer