Rails migrations best practices

Avoid using Rails models in migration.

Reasons:

  1. Models might have some lifecycle callbacks which we dont want to be invoked in a migration.
  2. As we know what we are doing we dont want to deal with validations.
  3. Model names can change irrespective of db table.
  4. Try to use raw sql as close as possible.

Squash them after a period of time.

Reasons:

  1.  To my experience over a period of time these migration files are painful and useless.
  2. Every rake db:migrate might take a few seconds, or creating of a new database might take a few minutes when these files are big. Consider using tools like squasher.

Make them irreversible.

Reason:

In Production it makes sense to have IrreversibleMigration as the code is tested in lower environments. If there is an issue try to fix it with a follow up migration.

Note: If there is a new developer in your team and setting up their environment. Let them do `rake db:schema:load` to get latest db copy.

Git merge vs rebase

There is no hard and fast rule. But i am putting out when to use what based on my experience.

Merge if

  • you are in a big team working on a feature branch and you want to rebased from master. If you dont have all the commits you are in trouble.
  • When you find rebasing is becoming painful for no reason. like for every rebase step you need to fix the same lines of code again and again.
  • Not worried about one more additional commit and order of commits as they are going to be mixed up.

Rebase if

  • you dont want to change the commit history/log.
  • You want the commit history looks clean. As new work will be on top of everything.
  • when you have less code changes or you know how to deal with conflicts (more patience required practice meditation).
  • you branched off of feature branch to your own branch. You can do what ever you want as its your world.