【问题标题】:polymorphic .find_or_create_by with mongoid 2.0.1, on embedded document collections?在嵌入式文档集合上使用 mongoid 2.0.1 的多态 .find_or_create_by?
【发布时间】:2011-05-07 17:09:00
【问题描述】:

在之前发布的 Mongoid (2.0.beta.20) 中,我可以传递一个类类型作为 嵌入文档集合中 .find_or_create_by 块的第二个参数。 在 v2.0.1 中似乎不再是这种情况,但我仍然 需要做多态find_or_create_by。任何建议/指示 如何做到这一点?

我曾经这样做过:

SomeClass.childclass.find_or_create_by({:key => "value"}, InheritingChildClass)

现在我收到一个异常,说参数太多(2 比 1) 在 .find_or_create_by 上。

当使用 find_or_create_by 时,如何告诉集合创建正确类型的对象?或者,我如何创建自己的方法,该方法在功能上与我想要的相同,并且可以在我的嵌入式文档集合中重复使用?

感谢任何帮助。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 inheritance polymorphism mongoid


    【解决方案1】:

    我最终为此推出了自己的解决方案

    module Mongoid::Relations
      class Many
        def find_or_new(attrs, type, &block)
          inst = self.where(attrs).first
    
          unless inst
            inst = type.new
            inst.write_attributes attrs
            self << inst
          end
    
          inst
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      不确定我是否真的理解您需要通知子类,但请查看以下要点:https://gist.github.com/960684

      我确实搜索子类实例而不需要通知它。也许你的场景确实需要它,但如果需要,为什么不调用子类的 find_or_create_by 呢?

      【讨论】:

      • 嗯,现在我明白了'- - .. 如果你想要 Person.find_or_create_by 之类的东西来生成子类实例,这可能是个问题。
      • 是的。另外 - 我似乎无法调用 InheritingChildClass.find_or_create_by。它抛出异常说我无法直接访问该类并且必须使用该集合。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多