Save inherited object for separate collection in Mongoid

I read before inheritance in mongoid and it seems that all the inherited classes will be stored in the base class, for example.

class BaseClass end class ChildClass1 < BaseClass end class ChildClass2 < BaseClass end 

It seems that they are all stored in the BaseClass collection.

I really want them to be stored in separate collections, for example. ChildClass1 - collection and ChildClass2 - collection .

+8
collections inheritance ruby-on-rails mongodb mongoid
source share
3 answers

I understand that this was published a year ago, but it could be what you were looking for:

 class BaseClass include Mongoid::Document def self.inherited(subclass) super subclass.store_in subclass.to_s.tableize end end class ChildClass1 < BaseClass end class ChildClass2 < BaseClass end 
+4
source share

This is impossible to do. Because this is the concept of STIs in Mongoid, as explained by Durran to the creator of Mongoid

If you really want to keep in several collections, you need to use a module, for example:

 class BaseClass include MyModule end class ChildClass1 include MyModule end class ChildClass2 include MyModule end 
+3
source share

Try using this approach:

 module Base extend ActiveSupport::Concern include Mongoid::Document include Mongoid::Timestamps included do # Common code goes here. end end class ChildClass1 include Base end class ChildClass2 include Base end 

I do this in my Rails 5 application and it works for sure.

0
source share

All Articles