How to turn off auto_increment in Rails Active Record
To disable auto increment as of Rails 5 you can simply pass
default: nil
for instance
create_table :table_name, id: :bigint, default: nil do |t|
# ... fields ...
end
That didn't work for me, but the following did:
create_table(:table_name, :id => false) do |t|
t.column :id, 'int(11) PRIMARY KEY'
end
Only problem is that you lose it in the schema.rb.
Okay, the question is old and the OP did not specify versions. None of the answers given here worked for me with these versions:
mysql2 0.3.11
rails 3.2.13
mysql 5.5
I ended up going for this:
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
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
+---------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
table with my solution:
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
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 key
HTH someone
Try this?
create_table(:table_name, :id => false) do |t|
t.integer :id, :options => 'PRIMARY KEY'
end