【发布时间】:2018-01-11 05:54:33
【问题描述】:
我将在一个应用程序中利用 Mongoid 的单一集合继承。但是,有一个地方我想禁用此功能。我正在考虑数据库迁移(使用mongoid_rails_migrations gem),我在其中重新定义模型以使我的迁移更易于维护。在这种情况下,我希望将 _type 字段视为普通属性。
如何在Mongoid中实现?
【问题讨论】:
标签: ruby-on-rails mongoid
我将在一个应用程序中利用 Mongoid 的单一集合继承。但是,有一个地方我想禁用此功能。我正在考虑数据库迁移(使用mongoid_rails_migrations gem),我在其中重新定义模型以使我的迁移更易于维护。在这种情况下,我希望将 _type 字段视为普通属性。
如何在Mongoid中实现?
【问题讨论】:
标签: ruby-on-rails mongoid
尝试this article 中提供的解决方案。定义以下模块并将其包含在要禁用单个集合继承的模型中。
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
这篇文章来自 2015 年,自那以后 Mongoid 可能发生了一些变化,因此您可能需要稍微调整一下这个解决方案。但无论如何,它应该会给你一个好的开始。
【讨论】: