Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating some objects from one database to another

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?

like image 645
fl00r Avatar asked Dec 04 '22 08:12

fl00r


2 Answers

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
...
like image 137
fl00r Avatar answered Dec 11 '22 16:12

fl00r


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.

like image 38
Vasiliy Ermolovich Avatar answered Dec 11 '22 15:12

Vasiliy Ermolovich