Save inherited object to separate collection in Mongoid Save inherited object to separate collection in Mongoid mongodb mongodb

Save inherited object to separate collection in Mongoid


I realise this was posted a year ago, but this might be what you were looking for:

class BaseClass  include Mongoid::Document  def self.inherited(subclass)    super    subclass.store_in subclass.to_s.tableize  endendclass ChildClass1 < BaseClassendclass ChildClass2 < BaseClassend


I encountered the same problem and did not find a good solution on the web.After few attempts, I developed a solution:

class A  include Mongoid::Document  include Mongoid::Timestamps  ...endclass B < A  def self.collection_name    :your_collection_name_1  end  ...endclass C < A  def self.collection_name    :your_collection_name_2  end   ...end

Before any access to mongo collection, mongoid gets the collection name from 'collection_name' method.

This way, I override the method 'collection_name' of mongoid class, which returns the collection name (instead of the name of the base class with 's': 'As')

So, all the write (or read) commands from class B will insert (select) into 'your_collection_name_1' collection and class C will insert into 'your_collection_name_2' collection.


It's impossible to do that. Because it's the concept of the STI In Mongoid like explain by Durran the Mongoid creator

If you really want save in several collection you need use Module include like :

class BaseClass  include MyModuleendclass ChildClass1  include MyModuleendclass ChildClass2  include MyModuleend