Rails Data Migrations
Have you ever run into a problem when alongside with DB schema migrations (managed by
rake db:migrate in Rails)
you have to often change your DB content, as well? If you read this, you probably tried to use schema migrations do change your data after schema changes, but this is not a recommended way and sometimes data changes could take a long time, so they will block your app at the deploy time.
Another approach is to use rake tasks to run your changes after
db:migrate or even independently. But this could also become a mess after some time if you have multiple developers in your project, and you need to change your data often.
This is our solution we came up with in our company - run data migration tasks in a
To create a data migration you need to run:
rails generate data_migration migration_name
and this will create a
migration_name.rb file in
db/data_migrations folder with a following content:
class MigrationName < DataMigration def up # put your code here end end
so all we need to do is to put some ruby code inside the
Finally, at the release time, you need to run
This will run all pending data migrations and store migration history in
data_migrations table. You're all set.
Rails 4.0 and higher
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install rails-data-migrations
- Fork it
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'Add some feature')
- Run tests (
appraisal install && appraisal rake)
- Push to the branch (
git push origin my-new-feature)
- Create new Pull Request
The gem is available as open source under the terms of the MIT License.