Reputation: 6597
I currently have an existing model, Document, that needs a new, auto-incrementing column. Unfortunately, I am getting errors during the migrate.
The steps I have taken are:
ruby script/generate migration add_index_column_to_Document
which properly generated the empty .rb
titled
20121220182429_add_index_column_to_document.rb
Next, I edited the file to look like:
class AddIndexColumnToDocument < ActiveRecord::Migration
def self.up
execute 'ALTER TABLE documents ADD index INT NOT NULL AUTO_INCREMENT PRIMARY KEY'
end
def self.down
execute 'ALTER TABLE documents DROP index'
end
end
Then I executed the migration with rake db:migrate
and got the following error:
== AddIndexColumnToDocument: migrating =======================================
-- execute("ALTER TABLE documents ADD index INT NOT NULL AUTO_INCREMENT PRIMARY KEY")
rake aborted!
An error has occurred, all later migrations canceled:
Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY' at line 1: ALTER TABLE documents ADD index INT NOT NULL AUTO_INCREMENT PRIMARY KEY
The MySQL version, according to apt-cache show mysql-server
is: 5.5.28-0ubuntu0.12.04.2
Unfortunately for me, my SQL code matches that of all examples I can find online, so I am unsure as to why it is not working. Thanks in advance for any help you may provide.
Upvotes: 0
Views: 1553
Reputation: 35533
Try escaping the word 'index' which is reserved. Even better, let Rails do it for you:
class AddIndexColumnToDocument < ActiveRecord::Migration
def change
add_column :documents, :index, :primary_key
end
end
Upvotes: 4