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

Getting associated objects for classes in modules

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 7.0.5
    • Component/s: Associations
    • Labels:
    • Environment:
      Debian 10.2, mongo:3.4.22-xenial container

      An object in a module will not get associated objects. Look at the code below. The company object in module Test1 does not behave as expected. c.emails should have been an array of 1. The workaround is to use an explicit class name as shown in module Test2.

      require "mongoid"
      
      Mongoid.load!('mongoid.yml', 'development')
      
      module Test1
        class Company
          include Mongoid::Document
          has_many :emails
        end
      
        class Email
          include Mongoid::Document
          belongs_to :company
        end
      end
      
      module Test2
        class Company
          include Mongoid::Document
          has_many :emails, class_name: "Test2::Email"
        end
      
        class Email
          include Mongoid::Document
          belongs_to :company, class_name: "Test2::Company"
        end
      end
      
      class Company
        include Mongoid::Document
        has_many :emails
      end
      
      class Email
        include Mongoid::Document
        belongs_to :company
      end
      
      def test(mod)
        # setup
        c = eval("#{mod}::Company.create")
        e = eval("#{mod}::Email.create")
        e.company = c
        c.save
        e.save
        c.reload
      
        # check the emails array
        puts c.emails
        if c.emails.size == 1
          puts "success"
        else
          puts "failure"
        end
      
        # teardown
        c.destroy
        e.destroy
      end
      
      test("Test1")   # fails. Expecting a success
      test("Test2")   # succeeds
      test("")            # succeeds
      
      

       

            Assignee:
            Unassigned Unassigned
            Reporter:
            ap_junk@mylinkx.com Amar Parmar
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: