Skip to content

Instantly share code, notes, and snippets.

@shimotori
Created June 26, 2012 20:32
Show Gist options
  • Save shimotori/2998735 to your computer and use it in GitHub Desktop.
Save shimotori/2998735 to your computer and use it in GitHub Desktop.
ActiveRecordモデルのデータをMongoidモデルに変換
# ARモデルに追加
# Mongoid向けのハッシュを生成
def gen_hash_for_mongoid
hash = {}
self.attributes.each_pair do |k1, v|
k2 = k1 + ((k1.match(/^id$/) || k1.match(/_id$/)) ? '_ar' : '') # PK, FKには後ろに_arを付ける
hash[k2] = v
end
hash
end
# Mongoidモデルに追加
# ARのデータをコンバート(個別追加)
def self.convert_ars_each
eval("Ar::" + self.name).all.each do |ar|
self.create! ar.gen_hash_for_mongoid
end
end
# ARのデータをコンバート(一括)
def self.convert_ars
self.collection.insert self.gen_ar_hashes
end
# ARからハッシュを生成
def self.gen_ar_hashes
data = []
eval("Ar::" + self.name).all.each do |ar|
data << ar.gen_hash_for_mongoid
end
data
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment