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

Eager loading doesn't really work with has_many relations.

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • None

      Tested version - 3.1.2.

      In the docs you state that this should work:

      class Band
      include Mongoid::Document
      has_many :albums
      end

      class Album
      include Mongoid::Document
      belongs_to :band
      end

      Band.includes(:albums).each do |band|
      p band.albums.first.name # Does not hit the database again.
      end

      So I did this:

      class Band
      include Mongoid::Document
      has_many :albums
      end

      class Album
      include Mongoid::Document
      belongs_to :band
      field :name
      end

      Album.create(band_id: Band.create.id)
      Album.create(band_id: Band.create.id)

      And then did this with logging:

      Band.includes(:albums).each do |band|
      p band.albums.first.name # Does not hit the database again.
      end

      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=bands selector={} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (0.3102ms)
      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=albums selector={"band_id"=>{"$in"=>["514acafe5b9e05fdec000001", "514acafe5b9e05fdec000003"]}} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (0.3438ms)
      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=albums selector={"$query"=>

      {"band_id"=>"514acafe5b9e05fdec000001"}

      , "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (0.5193ms)
      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=albums selector={"$query"=>

      {"band_id"=>"514acafe5b9e05fdec000003"}

      , "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (0.2167ms)

      So it does hit the database again.

            Assignee:
            arthurnn Arthur Nogueira Neves
            Reporter:
            exoth Yuriy Trofimenko
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: