我目前有一个现有的模型Document,它需要一个新的自动递增列。不幸的是,我在迁移期间遇到错误。
我采取的步骤是:
ruby script/generate migration add_index_column_to_Document
正确生成了标题为<{p}>的空.rb
20121220182429_add_index_column_to_document.rb
接下来,我将文件编辑为:
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
然后我用rake db:migrate
执行了迁移并收到以下错误:
== 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
根据apt-cache show mysql-server
,MySQL版本是: 5.5.28-0ubuntu0.12.04.2
不幸的是,我的SQL代码与我在网上找到的所有示例相匹配,所以我不确定它为什么不起作用。提前感谢您提供的任何帮助。
答案 0 :(得分:4)
尝试转义保留的'index'一词。更好的是,让Rails为你做:
class AddIndexColumnToDocument < ActiveRecord::Migration
def change
add_column :documents, :index, :primary_key
end
end