Mark S.
Mark S.

Reputation: 1546

Rails/Mongoid database migrations

I am currently working on a rails app where we are using mongoid/mongoDB on the back-end. I understand that I don't need ActiveRecord like migration to migrate the schema, but I do need to migrate data as I change mongoid model definitions. Is anyone else out there running into the same scenario, if so how are you handling it?

Upvotes: 2

Views: 5936

Answers (4)

Andrew
Andrew

Reputation: 238617

Even though you're not making schema changes, you may need to move data between fields, or remove fields that are no longer used in the codebase. It's nice to have migrations that you can run when you deploy new code. I recommend using a gem called mongoid_rails_migrations. This provides you with migration generators like you're used to and provides some organization to migrating data.

class MyMigration < Mongoid::Migration

  def self.up
    MyModel.all.each do |model|
      # label was renamed to name
      model.set :name, model[:label] # copy the data from the old field to the new one
      model.remove_attribute :label # remove the old field from the document
      model.save!
    end
  end

end

Upvotes: 8

Sny
Sny

Reputation: 1

I had the some scenario recently, where I have to do some data migration only once (basically update dirty data); So what I did have a mongoid migrations in /db/migrate/ and override the db:migrate task so that it creates a collection in mongo db of that app itself, say "migrations", that record the migration that got fired, with that, none of the migration will run again, and you can keep adding migrations with some hierarchy (if in case migration is interdependent).

Upvotes: 0

Alexis Perrier
Alexis Perrier

Reputation: 692

This question addresses the same issue of creating custom migrations in a mongoid setup.

Runtime changing model with mongodb/mongoid

Upvotes: 0

cpjolicoeur
cpjolicoeur

Reputation: 13106

Write a custom rake task to migrate the data as needed

Upvotes: 1

Related Questions