对我来说,创建模型、运行迁移、销毁它并再次创建相同的模型报告 SQL 异常,这对我来说似乎很奇怪:
project|master ⇒ rails g model name name
invoke active_record
create db/migrate/20130417185814_create_names.rb
create app/models/name.rb
project|master⚡ ⇒ rake db:migrate
== CreateNames: migrating ====================================================
-- create_table(:names)
-> 0.0020s
== CreateNames: migrated (0.0021s) ===========================================
project|master⚡ ⇒ rails d model name
invoke active_record
remove db/migrate/20130417185814_create_names.rb
remove app/models/name.rb
project|master⚡ ⇒ rake db:migrate
project|master⚡ ⇒ rails g model name test
invoke active_record
create db/migrate/20130417185845_create_names.rb
create app/models/name.rb
project|master⚡ ⇒ rake db:migrate
== CreateNames: migrating ====================================================
-- create_table(:names)
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "names" already exists: CREATE TABLE "names" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "test" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL) /path/project/db/migrate/20130417185845_create_names.rb:3:in `change'
-- create_table("names", {:force=>true})
-> 0.0100s
-- initialize_schema_migrations_table()
-> 0.0025s
-- assume_migrated_upto_version(20130417185814, ["/path/project/db/migrate"])
-> 0.0010s
You have 1 pending migrations:
20130417185845 CreateNames
Run `rake db:migrate` to update your database then try again.
也许,我做错了什么?迁移有删除表的代码 - 它是否只能用于回滚?
解决方案
删除模型和数据库表并生成一个新表非常简单:
- 创建模型:
rails g model user name
- 进行迁移:
rake db:migrate
- 实现一个东西,突然想起需要删除模型
- 还原特定迁移:
rake db:migrate:down VERSION=20130417185814
,20130417185814
迁移id在哪里(可以在rake db:migrate:status中看到) - 移除模型:
rails d model user
- 突然想起你需要这个模型,但是还有其他字段
- 创建模型:
rails g model user email group:references
- 成功迁移数据库:
rake db:migrate