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

klass method of polymorphic association item raises uninitialized constant error

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Backlog
    • Major - P3
    • Resolution: Unresolved
    • 7.0.13
    • None
    • Associations

    Description

      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
      

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated: