Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aputs/338623 to your computer and use it in GitHub Desktop.

Select an option

Save aputs/338623 to your computer and use it in GitHub Desktop.
activerecord for mongodb wrapper
# The basic idea is that we take the existing data via ActiveRecord
# and create new documents in MongoDB using MongoMapper.
# This method is necessary as we want to keep all the associations of existing dataset
# and by the way, clean up empty columns
# We rely on models still being ActiveRecord::Base, I bet you can figure out how the look like.
# And have the newer MongoDB ones here in a module, painful as we have to set the collection_name
# Don't put a +timestamps!+ into your MongoMapper models yet because this would change the updated_at if existing
module MongoStream
class Photo
@collection_name = 'photos'
include MongoMapper::Document
end
class Source
include MongoMapper::EmbeddedDocument
end
class Album
include MongoMapper::EmbeddedDocument
has_many :photos, :class_name => "MongoStream::Photo"
end
class Page
include MongoMapper::EmbeddedDocument
has_many :photos, :class_name => "MongoStream::Photo"
end
class User
@collection_name = 'users'
include MongoMapper::Document
has_many :sources, :class_name => "MongoStream::Source"
has_many :websites, :class_name => "MongoStream::Website"
end
class Website
@collection_name = 'websites'
include MongoMapper::Document
has_many :pages, :class_name => "MongoStream::Page"
has_many :users, :class_name => "MongoStream::User"
has_many :photos, :class_name => "MongoStream::Photo"
has_many :albums, :class_name => "MongoStream::Album"
end
end
class MigrateToMongodb < ActiveRecord::Migration
require 'mongo_mapper'
def self.clean_attrs(attributes)
attributes.reject{|k,v|k=="id" || v.nil?}
end
def self.up
%w(MongoStream::User MongoStream::Website MongoStream::Photo).map{|klass| instance_eval("#{klass}.delete_all") rescue nil }
::User.all.each do |user|
m_user = MongoStream::User.create!(clean_attrs(user.attributes))
user.sources.all.each do |source|
m_source = MongoStream::Source.new(clean_attrs(source.attributes))
source.photos.each do |photo|
p = MongoStream::Photo.create!(clean_attrs(photo.attributes))
p[:tags] = photo.tag_list.to_a
p[:source_id] = m_source.id
p.save
end
m_source.save
m_user.sources << m_source
end
m_user.save
end
end
def self.down
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment