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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With