Search code examples
ruby-on-railsmongoiddatabase-migrationrails-migrations

Managing mongoid migrations


Can someone give me a short introduction to doing DB migrations in Rails using Mongoid? I'm particularly interested in lazy per document migrations. By this, I mean that whenever you read a document from the database, you migrate it to its latest version and save it again.

Has anyone done this sort of thing before? I've come across mongoid_rails_migrations, but it doesn't provide any sort of documentation, and although it looks like it does this, I'm not really sure how to use it.

I should point out I'm only conceptually familiar with ActiveRecord migrations.


Solution

  • If you want to do the entire migration at once, then mongoid_rails_migrations will do what you need. There isn't really much to document, it duplicates the functionality of the standard ActiveRecord migration. You write your migrations, and then you use rake db:migrate to apply them and it handles figuring out which ones have and haven't been ran. I can answer further questions if there is something specific you want to know about it.

    For lazy migrations, the easiest solution is to use the after_initialize callback. Check if a field matches the old data scheme, and if it does you modify it the object and update it, so for example:

    class Person
        include Mongoid::Document
    
        after_initialize :migrate_data
    
        field :name, :type => String
    
        def migrate_data
            if !self[:first_name].blank? or !self[:last_name].blank?
                self.set(:name, "#{self[:first_name]} #{self[:last_name]}".strip)
                self.remove_attribute(:first_name)
                self.remove_attribute(:last_name)
            end
        end
    end
    

    The tradeoffs to keep in mind with the specific approach I gave above:

    If you run a request that returns a lot of records, such as Person.all.each {|p| puts p.name} and 100 people have the old format, it will immediately run 100 set queries. You could also call self.name = "#{self.first_name} #{self.last_name}".strip instead, but that means your data will only be migrated if the record is saved.

    General issues you might have is that any mass queries such as Person.where(:name => /Foo/).count will fail until all of the data is migrated. Also if you do Person.only(:name).first the migration would fail because you forgot to include the first_name and last_name fields.