DEV Community

Rahul
Rahul

Posted on

Recent Favorite Rails Tip!

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
Enter fullscreen mode Exit fullscreen mode

generates the following file

class AddEmailToUsers < ActiveRecord::Migration[5.0]
 def change
   add_column :users, :email, :string
 end
end
Enter fullscreen mode Exit fullscreen mode

After that, you just run

rake db:migrate
Enter fullscreen mode Exit fullscreen mode

Making a change to the database hardly takes a minute!

But consider this scenario where you created a table and started working on it.

source code 2

Now for some reasons, you want to rename the column names and also add another column to it.

source code

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 20200827072540
  • Remove the entry from the schema_migrations table
  • Drop the table transaction_dumps
  • Run the migration rake db:migrate again

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
Enter fullscreen mode Exit fullscreen mode

Neat right.

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
rake db:migrate
Enter fullscreen mode Exit fullscreen mode

There is a Rails way to do this and this is my recent favourite go-to option when I am playing with the migrations.

rake db:migrate:redo
Enter fullscreen mode Exit fullscreen mode

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 STEP.

rake db:migrate:redo STEP=2
Enter fullscreen mode Exit fullscreen mode

output

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.

Top comments (0)