Rails migrations over an existing database

谁说我不能喝 提交于 2019-12-13 13:13:40

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6807172/rails-migrations-over-an-existing-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!