【问题标题】:Migrating some objects from one database to another将一些对象从一个数据库迁移到另一个
【发布时间】:2011-08-07 17:11:00
【问题描述】:

如何从一个数据库(开发、sqlite)中转储一个用户及其所有关联(cmets、帖子等)以将其插入另一个数据库(生产、mysql)。

我应该将它转储到 yaml 还是 sql 或其他东西?

【问题讨论】:

    标签: mysql ruby-on-rails ruby sqlite dump


    【解决方案1】:

    好的。

    God Save the YAML

    我已经使用 YAML 从开发中转储到文件中并将其加载到我的生产中。由于它是 auto_increment,所以有 id 的 hack,它已经改变了。

    开发

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

    生产

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

    【讨论】:

    • 注意 Rails 3.1+ 使用 user.dup.save
    • 添加到 George Chen 的评论:对于 Rails 3.1+ 使用 post = p.dup
    【解决方案2】:

    你可以使用这个 gem:https://github.com/ludicast/yaml_db

    YamlDb 是独立于数据库的 转储和恢复数据的格式。 它补充了 独立于数据库的模式格式 在 db/schema.rb 中找到。数据是 保存到 db/data.yml 中。

    【讨论】:

    • 我知道这颗宝石。它非常好,我经常在我的开发中使用它来转储和加载。但这不是我需要的。它转储了整个数据库,但我只需要传输我需要的确切数据。
    • 其实我不知道关联,但是这家伙添加了一个表转储github.com/ludicast/yaml_db/pull/14。也许会有所帮助。
    • 不,我仍然需要转储确切的对象(数据库中的行)。无论如何,谢谢:) 我现在将我的对象转储到 YAML 中。它有效,但对我来说看起来很粗鲁,所以我问了这个问题
    • 我添加了我用过的解决方案
    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多