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

Default order in `embeds_many` association causes association to use/return stale data

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 7.1.0.rc0, 7.0.13
    • Affects Version/s: 7.0.1, 7.0.2
    • Component/s: Associations
    • Environment:
      mongoid-7.0.1
      MongoDB shell version v3.4.7
      ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
    • Fully Compatible

      It seems like adding the order clause to the definition of `embeds_many` relation produces incorrect results of queries. The following spec shows the problem. Commenting `order: :id.desc` out or reloading `manufactory` object fixes the latest expectation.

      require "spec_helper"
      
      class Manufactory
        include Mongoid::Document
      
        embeds_many :products, order: :id.desc # here
      end
      
      class Product
        include Mongoid::Document
      
        embedded_in :manufactory
      
        field :name, type: String
      end
      
      describe "the problem with associations" do
        let(:manufactory) { Manufactory.create }
      
        it "returns correct results" do
          product = Product.new
          product.manufactory = manufactory
          product.name = "car"
          product.save!
      
          expect(manufactory.products.count).to eq(1)
          expect(manufactory.products.where(name: "car").count).to eq(1)
        end
      
        context "when the association is already loaded by the query with a selector" do
          before { manufactory.products.where(name: "car").first }
      
          it "requires reload to return correct results" do
            product = Product.new
            product.manufactory = manufactory
            product.name = "car"
            product.save!
      
            expect(manufactory.products.count).to eq(1)
            expect(manufactory.products.where(name: "car").count).to eq(1) # fails (0 results)
            # expect(manufactory.reload.products.where(name: "car").count).to eq(1) # passes
        end
      end
      

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            markowy Marek Gierlach
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: