Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Mongoid inheritance? (Ingore _type field)

I am going to leverage Mongoid's single collection inheritance in one application. However, there is one place where I'd like to disable this feature. I am thinking about database migrations (with mongoid_rails_migrations gem), where I redefine models to make my migrations more maintainable. In this case, I'd like the _type field to be treated as an ordinary attribute.

How to achieve it in Mongoid?

like image 683
skalee Avatar asked Jan 11 '18 05:01

skalee


1 Answers

Try the solution provided in this article. Define the following module and include it in models where you want to disable single collection inheritance.

module NoHeritage
  extend ActiveSupport::Concern

  included do
    # Internal: Preserve the default storage options instead of storing in the
    # same collection than the superclass.
    delegate :storage_options, to: :class
  end

  module ClassMethods
    # Internal: Prevent adding _type in query selectors, and adding an index
    # for _type.
    def hereditary?
      false
    end

    # Internal: Prevent Mongoid from defining a _type getter and setter.
    def field(name, options = {})
      super unless name.to_sym == :_type
    end

    # Internal: Preserve the default storage options instead of storing in the
    # same collection than the superclass.
    def inherited(subclass)
      super

      def subclass.storage_options
        @storage_options ||= storage_options_defaults
      end
    end
  end
end

The article is from 2015 and it is possible that there were some changes in Mongoid since, so you may need to tweak this solution a little. But anyway it should give you a good start.

like image 143
Michał Młoźniak Avatar answered Nov 10 '22 22:11

Michał Młoźniak