简体   繁体   中英

Rails 5: Why does rails add column to schema.rb even though I've deleted the migration file

I created a migration:

class AddFormCounterToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :form_count, :integer, default: 0
  end
end

I ran rails db:migrate but soon realised I had renamed the column incorrectly. So I ran git reset master --hard -- so that the migration file was removed and schema.rb was reset -- and started again:

class AddFormCounterToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :forms_count, :integer, default: 0
  end
end

But when I ran rails db:migrate this time, not only was the new column created but also the old one.

  t.integer "form_count", default: 0
  t.integer "forms_count", default: 0

Wuh? So I ran rails db:rollback to see if that would work. But that fails with the error: No migration with version number 20181025092233. Since I hadn't committed that file, I believe there isn't a way of restoring it.

Where and why is this migration persisting? What's the best practise when deciding to remove and redo a migration? What's the best way out of this pickle? Is there any way other than running rails db:reset ? (I'm using Postgres.)

I think you have two solutions here. Either your recreate the exact migration file you destroyed (with the correct timestamp), and you'll be able to rollback from here rails db:rollback and delete it. The schema will be destroyed accordingly.

Another solution: rails hold all the migration it has done in a database table called schema_migrations . When you migrated the database, a corresponding entry in the schema_migrations was created. When you deleted the migration file by reseting on master, you didn't delete that entry in the table. So you can do this:

rails dbconsole

Once in the console

SELECT * FROM schema_migrations;

you'll see all the timestamps from the migrations you made on the database, the one you thought you deleted is here as well. Copy the timestamp and:

DELETE FROM schema_migrations WHERE version=$yourtimestamp;

Quit the db console and reset your database

First, do a database backup. Then, drop down your database ( rake db:drop ), after this delete your schema.rb and then, start to clean your project

rake db:schema:cache:clear
rake db:schema:cache:dump

Finally create your database again

rake db:create
rake db:migrate

Most of the time, just remove the "schema.rb" to avoid this kind of error. Always maintain the project organization through the console rails commands. Leave Git to control the versions of your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM