如何回滚到以前的迁移并删除架构中的表和列?

时间:2019-02-23 15:25:22

标签: ruby-on-rails ruby activerecord

我正在研究Rails 5项目,并且已经在一些表中添加了各种列,并且还创建了一个新表。显然,这已创建了一些迁移文件,我想恢复为某种迁移并删除此迁移后在架构中进行的所有更改。我该怎么做?

Schema.rb:

ActiveRecord::Schema.define(version: 20180814220216) do

  create_table "stores", force: :cascade do |t|
    t.string "name"
    t.string "address"
    t.float "beer_cost"
    t.text "facilities"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float "latitude"
    t.float "longitude"
    t.boolean "toilet"
    t.string "address_line2"
    t.string "address_line3"
    t.integer "user_id"
    t.integer "toilet_id"
    t.string "toilet_available"
  end

  create_table "toilets", force: :cascade do |t|
    t.string "toilet_available"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

运行rails db:migrate:status

后的输出
 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20180610144440  Create stores
   up     20180611145310  Change datatype beer cost
   up     20180611150425  Delete cig cost column
   up     20180611231832  Add longitude and latitude
   up     20180612194032  Add toilets column
   up     20180614125348  Add address line2 column
   up     20180614133234  Add address line3 column
   up     20180625201708  Devise create users
   up     20180625235156  Add user id to stores
   up     20180626124327  ********** NO FILE **********
   up     20180626124742  ********** NO FILE **********
   up     20180627115344  ********** NO FILE **********
   up     20180627115710  ********** NO FILE **********
   up     20180810102513  ********** NO FILE **********
   up     20180811094301  ********** NO FILE **********
   up     20180814220216  ********** NO FILE **********

2 个答案:

答案 0 :(得分:1)

您可以使用: rails db:rollback STEP=<put the number of migrations you want to go back

但是迁移仍然存在,如果您运行rails db:migrate,您仍然会看到所有这些更改。

因此,要么编写新的迁移以撤消先前的迁移,要么删除表。

或手动删除不需要的迁移文件。

答案 1 :(得分:1)

您不应该删除迁移,一旦删除,就无法回滚。正确的步骤顺序是rake db:rollback,然后然后删除迁移文件。

此时,最简单的解决方案是使用rails db打开SQL终端,并手动删除不需要的列/表,然后使用rake db:schema:dump更新您的{{1} }。