Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 242
Rudd Zwolinski Avatar asked Jul 28 '09 19:07

Rudd Zwolinski


People also ask

How rails db Migrate works?

When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.

How do I migrate a specific migration in rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What is db migration rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


1 Answers

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.

like image 126
jdl Avatar answered Oct 21 '22 23:10

jdl