开发者

Migrating some objects from one database to another

开发者 https://www.devze.com 2023-02-26 03:21 出处:网络
How can I dump one user with all his associations (comments, posts etc) from one database (development, sqlite) to insert it another (production, mysql).

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 in开发者_StackOverflowto yaml or to sql or something else?


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
...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号