Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save inherited object to separate collection in Mongoid

I read up to inheritance in mongoid and it seems that all inherited classes will save in the base class, e.g.

class BaseClass
end

class ChildClass1 < BaseClass
end

class ChildClass2 < BaseClass
end

It seems that all these store in the BaseClass collection.

I actually want them to store in separate collections, e.g. ChildClass1 - collection and ChildClass2 - collection.

like image 651
Boenne Avatar asked Mar 15 '12 16:03

Boenne


4 Answers

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
  end
end

class ChildClass1 < BaseClass
end

class ChildClass2 < BaseClass
end
like image 86
Ronna Avatar answered Oct 23 '22 14:10

Ronna


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
  ...
end


class B < A
  def self.collection_name
    :your_collection_name_1
  end
  ...
end


class 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.

like image 37
Assaf Faybish Avatar answered Oct 23 '22 12:10

Assaf Faybish


Please try 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 app and it works for sure.

like image 23
Slavik Shynkarenko Avatar answered Oct 23 '22 12:10

Slavik Shynkarenko


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 MyModule
end

class ChildClass1
  include MyModule
end

class ChildClass2
  include MyModule
end
like image 36
shingara Avatar answered Oct 23 '22 14:10

shingara