Rails is a powerful framework known for boosting productivity and being developer-friendly. There are many traits that help you in being productive. Let's talk about the one that I found very recently and how difficult was it to get the job done without it.
Rails migrations. If you haven't heard this term, in short, migrations help in changing the schema of your database. Read more here in case you're not familiar with it.
Rails provides scaffolding to create migration files. You need not create a migration file from scratch nor copy from the existing files. This is pretty standard.
rails generate migration add_email_to_users email:string
generates the following file
class AddEmailToUsers < ActiveRecord::Migration[5.0]
add_column :users, :email, :string
After that, you just run
Making a change to the database hardly takes a minute!
But consider this scenario where you created a table and started working on it.
Now for some reasons, you want to rename the column names and also add another column to it.
Since the migration already ran, these are the steps you're required to do to run the migration again.
- Get the migration version from the file name
- Remove the entry from the
- Drop the table
- Run the migration
This set of things gets really frustrating if you want to play around in your development or you're not really sure of the final schema.
A better way to do this is,
rake db:rollback #rolls back the latest migration change
rake db:migrate #runs all the pending migrations again
Hang on. This post ain't about this.
If you want to rollback multiple migration files and run them again, the headache is back. You have to get the migration versions and do,
rake db:migrate:down VERSION=20200827072540
rake db:migrate:down VERSION=20200825121103
There is a Rails way to do this and this is my recent favourite go-to option when I am playing with the migrations.
This rolls back the latest migration and runs the migration again. Here's the elegant part, if you want to redo the last
n migration files, you could just feed that as a variable
rake db:migrate:redo STEP=2
Easy and painless!
Always remember this, if you're doing something that takes too much time and makes you feel that Rails isn't fun to work with, you might be doing it the wrong way 😉
Thanks @Prathamesh for this tip.