Rails 在现有数据库上的迁移
我正在创建一个新的 Rails 3.1 应用程序。 我希望这个新应用程序重用现有数据库(由以前的 Rails 2 应用程序创建)。
我创建了新的应用程序定义模型,该模型重用数据库中的一些现有数据。
在开发和测试阶段,一切工作正常,因为它在干净的数据库上运行,但是当尝试部署到生产时,我收到诸如以下消息:
PGError: ERROR: column "email" of relation "users" already exists
*** [err :: localhost] : ALTER TABLE "users" ADD COLUMN "email" character varying(255) DEFAULT '' NOT NULL
但是我在迁移中认为
class DeviseCreateUsers < ActiveRecord::Migration
def change
change_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
t.timestamps
end
end
如何让 db:migrate 忽略已经存在的内容并且只改变新事物和/或新类型?
我在 stackoverflow 上看到了类似的问题,但没有人回答这个问题。感谢您的回答。
I am creating a new Rails 3.1 application.
I would like this new application to reuses an existing database (which was created by a previous rails 2 application).
I created the new application defining models that reuses some of the existing data in the database.
In the development and test phase everything works fine since it runs on a clean sheet database, but when trying to deploy to production I get messages such as:
PGError: ERROR: column "email" of relation "users" already exists
*** [err :: localhost] : ALTER TABLE "users" ADD COLUMN "email" character varying(255) DEFAULT '' NOT NULL
however I have in my migration thinks like
class DeviseCreateUsers < ActiveRecord::Migration
def change
change_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
t.timestamps
end
end
How can I make db:migrate ignore what already exist and only change the new things and/or new types?
I saw similar questions on stackoverflow, but none answering this question. Thanks for your answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用现有数据库,那么您不应该尝试通过迁移覆盖它,您应该复制 schema.rb 中的现有数据库,然后从那里向前迁移,仅添加已更改的字段。
If you are using an existing database then you shouldn't try and override it through migrations, you should replicate the existing database in schema.rb and then migrate forwards from there, only adding the fields that have changed.
我采取的一种方法是创建一个新模型(假设您还没有任何迁移 - 如果有,请小心删除它们),例如“rails 生成模型用户”。除此之外,生成器还为该模型创建数据库迁移。当您运行 db migraterails 时,rails 会创建 users 表并根据现有数据库的当前状态创建 schema.rb。从那时起,后续迁移将基于 schema.rb 和所做的任何新更改。
One approach I've taken is to create a new model (assuming you don't have any migrations yet - carefully delete them if you do), say, "rails generate model user". Among other things, the generator creates the db migration for that model. When you run the db migrate rails, rails creates the users table and creates a schema.rb based on the current state of the existing database. From then on subsequent migrations will be based on the schema.rb and any new changes made.