Migrating some objects from one database to anothe

2019-03-16 20:12发布

问题:

How can I dump one user with all his associations (comments, posts etc) from one database (development, sqlite) to insert it another (production, mysql).

Should I dump it into yaml or to sql or something else?

回答1:

Ok.

God Save the YAML

I've used YAML dumping into file from development and loading this in my production. There was hack with id, that have changed, due it is auto_increament.

development

user     = User.find X
posts    = user.posts
comments = user.comments
...
File.open("user.yml", "w")    { |f| f << YAML::dump(user) }
File.open("comments.yml", "w"){ |f| f << YAML::dump(comments) }
File.open("posts.yml", "w")   { |f| f << YAML::dump(posts) }
...

production

user     = YAML::load_file("user.yml")
posts    = YAML::load_file("posts.yml")
comments = YAML::load_file("comments.yml")
new_user = user.clone.save # we should clone our object, because it isn't exist
posts.each do |p|
  post = p.clone
  post.user = new_user
  post.save
end
...


回答2:

You can use this gem: https://github.com/ludicast/yaml_db

YamlDb is a database-independent format for dumping and restoring data. It complements the the database-independent schema format found in db/schema.rb. The data is saved into db/data.yml.