How can I migrate my database with rails to the first revision without dropping the database first?

百般思念 提交于 2019-12-17 23:18:49

问题


I have a database set up for my Rails installation and some migrations set up. I would like to be able to reset my database back down to having no tables/constraints/etc., but can't find a reasonable way to do this without knowing the number of migrations or the timestamp of the first migration. Here are my options as I see them:

  • rake db:migrate:reset
  • rake db:migrate:down VERSION=20090701154839 where 20090701154839 is the timestamp associated with the first migration
  • rake db:rollback STEP=15 where there have been 15 migrations

The problem with db:migrate:reset is that it drops the database first (it does db:drop, db:create, then db:migrate).

The problem with db:migrate:down is that I don't want to encode the VERSION of the beginning.

The problem with db:rollback is that I don't know the number of steps it is back to the beginning.

What are my options?


回答1:


rake db:migrate VERSION=0

It works even if you're using the newer timestamped migration files.

Update: I just tested this on Rails 3.2.1, and it still works. It runs the "down" part of all the migrations known to schema_migrations. I have no idea if it worked on 3.1 or not, but the comment below indicates that this feature was broken during that time.




回答2:


In addition to jdl's (correct) solution above, another hack-y way to acheive this is to do rake db:rollback STEP=1000000, where 1000000 is a large number, larger than the number of migrations you'll ever have. It will rollback as far as it can up to 1000000 times, or however many times you put as the STEP.




回答3:


It's moderately hackish, but you could do a query to find the first VERSION in schema_migrations and then call rake db:migrate:down to get that VERSION (I'm assuming you want to package up a "reset" script for your app).

That will, of course, require that the down methods on all your migrations work properly.



来源:https://stackoverflow.com/questions/1196310/how-can-i-migrate-my-database-with-rails-to-the-first-revision-without-dropping

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