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

'includes' doesn't work on has_many relations with default_scope.

    • Type: Icon: Task Task
    • Resolution: Done
    • 4.0.0 final
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      Tested on Mongoid 3.1.4:

      class Band
      include Mongoid::Document
      has_many :albums
      end

      class Album
      include Mongoid::Document
      belongs_to :band
      field :name
      default_scope where(name: 'foo')
      end

      Album.create(band_id: Band.create.id, name: 'foo')
      Album.create(band_id: Band.create.id, name: 'foo')

      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.3586ms)
      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=albums selector={"name"=>"foo", "band_id"=>{"$in"=>["51b58e5c5b9e053267000001", "51b58e5c5b9e053267000003"]}} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (0.3092ms)
      MOPED: 127.0.0.1:27017 QUERY database=gocheap_development collection=albums selector={"$query"=>

      {"name"=>"foo", "band_id"=>"51b58e5c5b9e053267000001"}

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

      {"name"=>"foo", "band_id"=>"51b58e5c5b9e053267000003"}

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

      So despite the fact that the query for 'includes' is done with the default_scope selector, the collected results are not used later.

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

              Created:
              Updated:
              Resolved: