Gitty Migrations Plugin for Rails
08/03/20
Migrations make it super easy to work with your database in Rails, with only a few small problem that I've run across.
Certain migrations rely on specific changelists
Most of the time, this is because you're dealing with a legacy database that you are trying to clean up and you are moving data around. You want everyone to get the changes, but don't want to rely on people running a rake task at a certain revision to implement the changes. To get around this we sometimes redefine a class in the migration to override the newer, updated class of the same name in our application. But what if we didn't have to do this, what if we could just tell the migration what revision or changelist the migration should run against and let it run. This is where gitty migrations would come in.
Here's how it's done. (this example was just done for the purpose of showing how the plugin works)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class ResetAllAccountTypes < ActiveRecord::Migration use_git_revision "42ca6c6de8cbd6591dcada7437c97000839e8074" # or if you've used git-tag to tag your revision # use_git_revision "v2.0" def self.up add_column :user, :account, :integer, :null => false User.find(:all).each do |user| user.account = case user.account_type when "Free" : Account::Types::Free when "Paid" : Account::Types::Paid else Account::Types::Unknown end end remove_column :user, :account_type end def self.down ... end end |
Now whenever a developer runs this migration, it will check out that revision of git, run the migration against it, and then change your git repository back to where it was. If in the future you decide to use an account type table instead of an enum and change all your code, this migration will still work.
TODO
- If you don't set a revision have it automatically use the revision you checked the migration in on.
Thoughts or comments? Have a better way of dealing with this. Let me know.
Comments
08/03/20 - Hongli Lai Says:
Cool! I’ve figured that the right way to solve the problem of merging migrations between different branches is to integrate with the version control system. Looks like this is a step towards the right solution.
08/04/05 - Eric Goodwin Says:
@Hongli, Glad you like it. It looks like migrations will be using UTC timecodes”> from now on, so that may solve part of your problem or will make it easier to merge anyways.