9

I'm writing a migration to convert a non-rails app into the right format for rails - one of the tables for some reason does not have auto increment set on the id column. Is there a quick way to turn it on while in a migration, maybe with change_column or something?

alf
  • 18,372
  • 10
  • 61
  • 92
DGM
  • 26,629
  • 7
  • 58
  • 79

3 Answers3

7

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)

Note this is just an example. The final SQL statement syntax depends on the database.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • thanks alot @Simone Carletti, wasted whole day to solve the problem, but now it's solved and thanks DGM too, for posting question specific to my case. Can you both give me idea on writing stored procedures in rails 4.1 in a fancy way, hoping you guys will help me again. Happy coding. – roarfromror Apr 10 '15 at 11:49
  • I don't know of much activity in rails using stored procedures - some corners of rails have little use for the more powerful sides of SQL, others just don't know about it... anyway, at the very least you could use this same form to write the SQL to create the stored procedure. – DGM Apr 10 '15 at 19:33
6

If you're on postgesql, a single request won't make it. You'll need to create a new sequence in the database.

create sequence users_id_seq;

Then add the id column to your table

alter table users
    add id INT UNIQUE;

Then set the default value for the id

alter table users
    alter column id
         set default nextval('users_id_seq');

Then populate the id column. This may be quite long if the table has many rows

update users
    set id = nextval('users_id_seq');

Hope this helps postgresql users...

jlfenaux
  • 3,263
  • 1
  • 26
  • 33
5

The Postgres answer by @jlfenaux misses out on the serial type, which does all of it for you automatically:

ALTER TABLE tbl add tbl_id serial;

More details in this related answer.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228