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

klass method of polymorphic association item raises uninitialized constant error

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 7.0.13
    • Component/s: Associations
    • Labels:

      Calling the klass method on a polymorphic association for an instance results in a NameError being raised. This seems to be due to how Mongoid::Association::Relatable#relation_class determines the name. Since it uses the field name when a class is not specified (like in a polymorphic situation) It tries to resolve a class name that doesn't exist. Then tries to call `Module#const_get` on the non-existant class name https://github.com/mongodb/mongoid/blob/f4eb37c9914d83afd27d3ac135afd568e1279a2f/lib/mongoid/association/relatable.rb#L444

       

      The following models should reproduce the error:

      class User
        include Mongoid::Document
      end
      
      class PolyModel
        include Mongoid::Document
        belongs_to :actor, polymorphic: true
      end
      
      model = PolyModel.new(actor: User.new)
      model.actor.klass   # raises NameError expecting to return User
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            yads12@gmail.com Vadim Kazakov
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: