I wrote a few migrations for my Rails 3 app, but I would like to change the order of the migrations. How can I change the migration order or sequence? Is it as simple as renaming the migration file with what appears to be the timestamp?
I know this is an odd question, but basically, I made a mess of my migrations and removed some old migrations and now I need to drop a table before creating a new one. I also know I can include the drop statement in the create-the-new-table migration, but I'm curious to know how to reorder migrations.
5 Changing Existing Migrations You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.
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.
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Unlike rake db:migrate that runs migrations that have not run yet, rake db:schema:load loads the schema that is already generated in db/schema. rb into the database. Always use this command when: You run the application for the first time.
Yes, it runs the migrations which have not been run in the order of the prefix. In earlier versions of rails, maybe 2.1
or 2.2
, they used to be numbered starting with 01
, but they switched to timestamps.
There is a table which keeps track of which migrations have run. The intentions is, multiple developers my have added migrations, and checked them in version control later. So, there may be a migration which has not run, but is numbered before the highest numbered migration which has run.
If you change the migration sequence, (and I have) it's better to first down version before all the migrations you are re-sequencing. Use the VERSION
option with db:migrate
. If the highest numbered migration that you want to keep (not run the down) is 20120318143249
, call it this way.
rake db:migrate VERSION=20120318143249
I often run the down on a migration, and re-run it until I get the details of the migration to my satisfaction. Sometimes I re-order them, when I want to work on one of them, and I want it to be the last.
Yes, the prefix on the filename is what determines the order of execution. However, keep in mind this will only change your current system if you wipe your DB/start over.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With