Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment a non-primary key field in Ruby on Rails

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.

like image 955
kingjeffrey Avatar asked Jul 10 '10 19:07

kingjeffrey


People also ask

Can you auto increment a non primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

Is auto increment always primary key?

A Primary Key just needs to be a unique value that identifies its entry from other entries, and not null. Save this answer. Show activity on this post. Primary key should be unique but not necessarily need to be auto_increment.

Can varchar be auto increment?

AutoIncrement fields are integer in mysql. You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.

Is it mandatory to make primary column of a table as auto increment?

No. A primary key must be unique and that has to be 100% guaranteed, and NON NULL A primary key should be stable if ever possible and not change. So you don't have to, but it's a good choice since there is no other naturally unique data and you don't want to have enormous primary keys.


1 Answers

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.

like image 174
user386660 Avatar answered Oct 08 '22 04:10

user386660