by testdouble

testdouble / good-migrations

Prevent Rails from auto-loading app/ code when running database migrations

220 Stars 6 Forks Last release: Not found MIT License 41 Commits 2 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:


Build Status

This gem prevents Rails from auto-loading app code while it's running migrations, preventing the common mistake of referencing ActiveRecord models from migration code.


Add good_migrations to your gemfile:

gem 'good_migrations'

And you're done! That's it.


Over the life of your Ruby on Rails application, your app's models will change dramatically, but according to the Rails guides, your migrations shouldn't:

In general, editing existing migrations is not a good idea. You will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require.

That means that if your migrations reference the ActiveRecord model objects you've defined in

, your old migrations are likely to break. That's not good.

By adding this gem to your project's

, autoloading paths inside
while running any of the
Rake tasks will raise an error, explaining the dangers inherent.

Some will reply, "who cares if old migrations are broken? I can still run

because I have a
file". The problem with this approach is that, so long as some migrations aren't runnable, the
can't be regenerated from scratch and its veracity can no longer be trusted. In practice, we've seen numerous projects accumulate cruft in
as the result of erroneous commits to work-in-progress migrations, leading to the development and test databases falling out of sync with production. That's not good!

For more background, see the last section of this blog post on healthy migration habits


There's no public API to this gem. If you want to work around its behavior, you have a few options:

  1. Run the command with the env var
  2. Explicitly
    the app code you need in your migration
  3. Remove the gem from your project


Credit for figuring out where to hook into the ActiveSupport autoloader goes to @tenderlove for this gist.


Because this gem works by monkey-patching the ActiveSupport auto-loader, it will not work if your Rails environment (development, by default) is configured to eager load your application's classes (see: config.eager_load).

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.