ruby 如何在Mongoid中为子类设置集合名称?

6mw9ycah  于 4个月前  发布在  Ruby
关注(0)|答案(2)|浏览(63)
class Foo
  include Mongoid::Document
end

class Bar < Foo
end

字符串
Foo.all返回Bars,Bar.all返回Foos。
我想把Foo和Bar放在不同的集合中。
我试

class Bar < Foo
  store_in collection: 'bars'


但得到

Mongoid::Errors::InvalidStorageParent:
Problem:
  Invalid store_in call on class Bar.
Summary:
  The :store_in macro can only be called on a base Mongoid Document


使用Mongoid 4.0.2

2admgd59

2admgd591#

您还需要将Bar设置为Mongoid文档。

class Bar < Foo
  include Mongoid::Document
  store_in collection: 'bars'

字符串

mbskvtky

mbskvtky2#

这个问题现在已经很老了,但Mongoid现在支持它。
以前,您必须使用所有公共逻辑创建一个模块,并将它们包含在两个模型类中。
从Mongoid v8.1开始,您可以使用store_in collection: "collection_name来完成此操作。

class Shape
  include Mongoid::Document
  store_in collection: :shapes
end

class Circle < Shape
  store_in collection: :circles
end

字符串
这将在2个不同的集合(形状和圆圈)中创建文档。
参考网址:https://www.mongodb.com/docs/mongoid/current/reference/inheritance/#persistence-contexts

相关问题