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

Getting associated objects for classes in modules

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Backlog
    • Minor - P4
    • Resolution: Unresolved
    • 7.0.5
    • None
    • Associations
    • Debian 10.2, mongo:3.4.22-xenial container

    Description

      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
      
      

       

      Attachments

        Issue Links

          Activity

            People

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

              Dates

                Created:
                Updated: