In a RoR migration, how do I auto increment a non-primary-key field? I'd like to do this in the db definition, and not in the model.
Asked
Active
Viewed 7,308 times
1 Answers
9
You need to execute an SQL statement.
statement = "ALTER TABLE `users` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT"
ActiveRecord::Base.connection.execute(statement)
you can entry manually in your migration
Note this is just an example. The final SQL statement syntax depends on the database.

berkes
- 26,996
- 27
- 115
- 206

user386660
- 501
- 1
- 3
- 12
-
2Am I correct in assuming by your answer that Rails does not provide a way to do this without direct execution of a SQL statement? I would expect something like: `t.integer :auto_i, :auto_increment => true` to work (but it does not). – kingjeffrey Jul 10 '10 at 19:41
-
3yes Rails does not provide :auto_increment keyword in migrations – user386660 Jul 10 '10 at 22:29
-
And if you want to all keywords or other good things in Rails then . " rubymine IDE for ROR " would be so useful. I am using for last 6 months. – user386660 Jul 10 '10 at 22:32
-
1Note that this is `mysql` specific solution. Postgres doesn't support `AUTO_INCREMENT`. Jump into this question for Postgres solution http://stackoverflow.com/questions/787722/postgresql-autoincrement – freemanoid Sep 17 '14 at 10:21