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

Eager loading broken when iterating criteria a second time

      Mongoid: 4 ( master at 35aea60 )

      Having a criteria like this:

      posts =  Post.all.includes(:person)
      

      The first time the posts are iterated the person is not fetched from the db - but the second time it is.

      require 'mongoid'
      require 'mongoid/support/query_counter'
      require 'minitest/autorun'
      # Ensure backward compatibility with Minitest 4
      Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
      
      Mongoid.configure.connect_to("mongoid_test")
      
      Mongoid.logger = Logger.new($stdout)
      Moped.logger = Logger.new($stdout)
      
      def count_queries(&block)
        query_counter = Mongoid::QueryCounter.new
        query_counter.instrument(&block)
        query_counter.events.size
      end
      
      class Post
        include Mongoid::Document
        belongs_to :person
      end
      
      
      class Person
        include Mongoid::Document
        has_many :posts
        field :name
      end
      
      class BugTest < Minitest::Test
        def test_query_count
          p = Person.create!(name: 'arthurnn')
          4.times { Post.create!(person: p) }
      
          criteria =  Post.all.includes(:person)
      
          query_counter = count_queries do
            criteria.each(&:person)
          end
      
          # this is fine
          assert_equal 2, query_counter
      
          query_counter = count_queries do
            criteria.each(&:person)
          end
      
          # this fails
          assert_equal 2, query_counter
        end
      end
      
      Finished tests in 0.114663s, 8.7212 tests/s, 17.4424 assertions/s.
      
        1) Failure:
      BugTest#test_query_count [examples/mongoid_test.rb:49]:
      Expected: 2
        Actual: 43
      
      1 tests, 2 assertions, 1 failures, 0 errors, 0 skips
      

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            nvloff nvloff
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: