Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
Mark S. Avatar asked Mar 16 '26 07:03

Mark S.


2 Answers

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
like image 84
Andrew Avatar answered Mar 19 '26 02:03

Andrew


Write a custom rake task to migrate the data as needed

like image 25
cpjolicoeur Avatar answered Mar 19 '26 02:03

cpjolicoeur