【问题标题】:mongoid convert has_many relation into embeds_manymongoid 将 has_many 关系转换为 embeds_many
【发布时间】:2012-08-04 13:12:14
【问题描述】:

不久前我犯了早期的新手 mongodb 错误,并在我应该嵌入它们的时候创建了很多 has_many 关系。

我的问题是我现在如何将我的记录从多态 has_many 场景转换为 embeds_many?

#Place.rb
has_many :images, as: :imageable, dependent: :destroy, autosave: true

#Image.rb
belongs_to :imageable, polymorphic: true

到 =>

#Place.rb
embeds_many :images, as: :imageable

#Image.rb
embedded_in :imageable, polymorphic: true

我通常会遍历所有记录并这样做,但我想命名会是一个问题。因此,我不确定如何在不创建临时模型的情况下完成此任务,但我希望其他一些人也犯了同样的错误并可能有一个温和的解决方案?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid embedded-resource mongoid3


    【解决方案1】:

    对于像我这样的人,以后看看这个问题!

    您可以通过将模型从 has_many 更改为 embeds_many(在 ruby​​ 基础代码中)来做到这一点,然后使用我为自己编写的这个 javascript:

    // Parent is parent model name without 's' and model is related model name without 's',
    // if you have something with plural name this function don't work
    // example : ref2em('user', 'post')
    var ref2em = function(parent, model) {
      var query, update;
      // Search through all instances
      db[parent+'s'].find().forEach(function(ref) {
        query = {};
        // Get all related models with parent_id
        query[parent+"_id"] = ref._id;
        db[model+'s'].find(query).forEach(function(em) {
          // Update parent with $push operator (add model to parent's models attribute)
          update = { $push: {} };
          update['$push'][model+'s'] = em;
          db[parent+'s'].update({_id: ref._id}, update);
        });
      });
    }
    

    然后使用类似的东西(将用户 has_many 帖子更新为用户 embeds_many 帖子):

    ref2em('user', 'post')
    

    (所有这些功能都只能在 mongo 控制台中使用,请确保您有备份并且知道自己在做什么,阅读我写的 cmets,最后删除旧集合)。

    没有保证,我只是分享我所做的事情(可能不适合你)。

    【讨论】:

      猜你喜欢
      • 2012-06-07
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多