Exception: Mongoid::Errors::UnrecognizedModelAlias

Inherits:
MongoidError
  • Object
show all
Defined in:
lib/mongoid/errors/unrecognized_model_alias.rb

Overview

Raised when a polymorphic association is queried, but the type of the association cannot be resolved. This usually happens when the data in the database references a type that no longer exists.

For example, consider the following model:

class Manager
  include Mongoid::Document
  belongs_to :unit, polymorphic: true
end

Imagine there is a document in the managers collection that looks something like this:

{ _id: ..., unit_id: ..., unit_type: 'Department::Engineering' }

If, at some point in your refactoring, you rename the Department::Engineering model to something else, Mongoid will no longer be able to resolve the type of this association, and asking for manager.unit will raise this exception.

To fix this exception, you can add an alias to the model class so that it can still be found, even after renaming it:

module Engineering
  class Department
    include Mongoid::Document

    identify_as 'Department::Engineering'

    # ...
  end
end

Better practice would be to use unique strings instead of class names to identify these polymorphic types in the database (e.g. ‘dept’ instead of ‘Department::Engineering’).

Constant Summary

Constants inherited from MongoidError

MongoidError::BASE_KEY

Instance Attribute Summary

Attributes inherited from MongoidError

#problem, #resolution, #summary

Instance Method Summary collapse

Methods inherited from MongoidError

#compose_message

Constructor Details

#initialize(model_alias) ⇒ UnrecognizedModelAlias

Returns a new instance of UnrecognizedModelAlias.



43
44
45
46
47
48
49
50
# File 'lib/mongoid/errors/unrecognized_model_alias.rb', line 43

def initialize(model_alias)
  super(
    compose_message(
      'unrecognized_model_alias',
      model_alias: model_alias.inspect
    )
  )
end