Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-5031

Document the need to preload child classes when using discriminator value override

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Minor - P4 Minor - P4
    • 7.2.1
    • Affects Version/s: 7.2.0
    • Component/s: Docs
    • None
    • Environment:
      Rails 5.2.3
      Ruby 2.6.6
    • Fully Compatible

      When using discriminator_value on child classes, it throws an exception when trying to retrieve that document from the parent class.

      ie.:

       

      class Parent
        include Mongoid::Document
      end
      
      class Child < Parent
        self.discriminator_value = 'ch'
      end

      So if I create a record, I can retrieve the record from both child and parent class:

       

      > Child.create
      => #<Child _id: 5fd29615a50a9012f69d1255 >
      > Child.last
      => #<Child _id: 5fd29615a50a9012f69d1255 >
      > Parent.last
      => #<Child _id: 5fd29615a50a9012f69d1255 >

      However, if I terminate the console session and start again, I get the following:

      ~ rails c
      > Parent.last
      Mongoid::Errors::UnknownModel ()
      message:
        Attempted to instantiate an object of the unknown model 'Ch'.
      summary:
        A document with the value 'ch' at the key '_type' was used to instantiate a model object but Mongoid cannot find the Class.
      resolution:
        The _type field is a reserved one used by Mongoid to determine the class for instantiating an object. Please don't save data in this field or ensure that any values in this field correspond to valid Models.
      > Child.last
      => #<Children _id: 5fd29615a50a9012f69d1255 >
      > Parent.last
      => #<Child _id: 5fd29615a50a9012f69d1255 >

       

       

       

       

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            mauricio@jewlr.com Maurício Ackermann
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: