2

The default inheritance method for Mongoid is creating a single collection for all subclasses. For instance:

class User
  include Mongoid::Document
end

class Admin < User
end

class Guest < User
end

Internally, Mongoid adds a _type field to each document with the class name, which is used to automatically map each instance to the right class.

The problem is, if I have a document in this collection with an unknown _type value, I get an exception:

NameError: uninitialized constant UnknownClass

This can happen if you create a new subclass of User, in the example above, and a migration that creates a new instance of this new subclass. Until you restart your servers, every query to this collection (like User.all.to_a). Is there a safe way to avoid this error?

The only solution I came up is rescuing NameError exception and querying by all known subclasses:

class User
  def self.some_query(params)
    self.where(params).to_a
  rescue NameError => e
    Rails.logger.error "Unknown subclass: #{e.message}"

    subtypes = self.descendants.map(&:to_s)
    self.where(params.merge(:_type.in => subtypes)).to_a
  end
end
4

0 回答 0