23

I have a Rails app, where one of the models does not have the id column. Doing some research I found the migration that created it:

create_table(:the_model, :id => false) do |t|
  # columns
end

Now, on a new migration, I want to add the id column in a Rails standard way (not using database specific sql). How can I do that?

I already tried this without success:

change_table(:the_model, :id => true) do |t|
end
alf
  • 18,372
  • 10
  • 61
  • 92

3 Answers3

49

You can either manually add the id column:

add_column :table_name, :id, :primary_key

or clear (or backup) your data, rollback to this migration, get rid of the option :id => false, and re-migrate.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
cdesrosiers
  • 8,862
  • 2
  • 28
  • 33
  • The command worked! Although I ended up recreating the table (`drop_table` and `create_table` in the migration) because it already had a primary key. Thanks a lot! – alf Sep 23 '12 at 01:00
  • 2
    By running the migration will the id column of the existing records automatically get populated with unique id values? If not, how/what do I assign them to keep the system happy? – George Shaw Oct 30 '12 at 18:34
  • 10
    When you tell rails to make the column :primary_key, it sets up the database in such a way that the db will automatically populate the id field for you. All your records will magically gain unique ids. – kepstin Dec 05 '14 at 22:45
8

You don't need to mention :integer

rails g migration add_id_to_model id:primary_key worked for me.

Prabhat Thapa
  • 81
  • 1
  • 3
4

You already got your answer, but here is a one liner that does all in this case

rails generate migration AddIdToModel id:integer

Look at the syntax of migration file name AddColumnNameToTableName followed the column description. It will generate something like below

class AddIdToModel < ActiveRecord::Migration
  def change
    add_column :models, :id, :integer
  end
end

Now you can change this line if you feel for anything else. and just run rake db:migrate.

Samiron
  • 5,169
  • 2
  • 28
  • 55