如何禁用Mongoid继承?(Ingore _type字段)

ska*_*lee 7 ruby-on-rails mongoid

我将在一个应用程序中利用Mongoid的单一集合继承.但是,有一个地方我想禁用此功能.我正在考虑数据库迁移(使用mongoid_rails_migrations gem),我重新定义模型以使我的迁移更易于维护.在这种情况下,我希望将该_type字段视为普通属性.

如何在Mongoid中实现它?

Mic*_*iak 1

尝试本文中提供的解决方案。定义以下模块并将其包含在要禁用单个集合继承的模型中。

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
Run Code Online (Sandbox Code Playgroud)

这篇文章是 2015 年的,自那以后 Mongoid 可能发生了一些变化,所以您可能需要稍微调整这个解决方案。但无论如何它应该给你一个好的开始。