B Seven
B Seven

Reputation: 45941

How to set the collection name in Mongoid for a subclass?

class Foo
  include Mongoid::Document
end

class Bar < Foo
end

Foo.all returns Bars, and Bar.all returns Foos.

I want to put Foo and Bar in separate collections.

I tried

class Bar < Foo
  store_in collection: 'bars'

but got

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

Using Mongoid 4.0.2

Upvotes: 8

Views: 5233

Answers (2)

Harsh2000
Harsh2000

Reputation: 11

This question is very old now but Mongoid now supports it out of the box.

Previously, you would have to make a module with all the common logic and include them in both the Model Classes.

From Mongoid v8.1 onwards, you can use store_in collection: "collection_name for this.

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

class Circle < Shape
  store_in collection: :circles
end

This will create the documents in 2 different collections (shapes and circles).

Reference: https://www.mongodb.com/docs/mongoid/current/reference/inheritance/#persistence-contexts

Upvotes: 1

Rob Wagner
Rob Wagner

Reputation: 4421

You need to make Bar a Mongoid document as well.

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

Upvotes: 14

Related Questions