Reputation: 747
In Rails Migration File is possible to create a column ID primary_key no auto_increment?
Upvotes: 3
Views: 3240
Reputation: 117
Seems, that Yuki´s answer got too old? It didn´t work for me. But the following worked:
class CreateNoAutoincrement < ActiveRecord::Migration[4.2]
def up
create_table( :my_table, :id => false ) {|t|
t.integer :id, null: false ;
t.string :token, null: false ;
}
add_index :my_table, :id, unique: true ;
add_index :my_table, :token, unique: true ;
end
def down
drop_table :my_table ;
end
end
On MariaDB the table looks like this:
MariaDB [foo_devel]> describe my_table ;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| token | varchar(255) | NO | UNI | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.001 sec)
It´s nice, that I still get a primary key, not just two Unique Indexes (probably because the column name is 'id')
Upvotes: 1
Reputation: 456
I succeeded dropping auto_increment by running following change_column method.
class DropAutoIncrement < ActiveRecord::Migration
def change
change_column :my_table, :id, :integer
end
end
I used activerecord 4.0.2.
Upvotes: 2