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

Custom scopes order messes up criteria dealing with _id

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

      Hello!

      I came across some strange behavior when using Mongoid criteria with custom scopes. I have the two following scopes defined for a mongoid document:

      class Author
        include Mongoid::Document
        identity type: Integer
      
        scope :for_ids, ->(author_ids) { where(:_id.in => author_ids) }
        scope :sort_fields, -> { only([:_id, :name]) }
      end
      

      Now, when I search authors for a set of ids using scope and use another scope, the criteria becomes weird leading to zero results:

      # this is OK
      1.9.3p0 :030 > Author.for_ids([39620832, 219395552])
       => #<Mongoid::Criteria
        selector: {:_id=>{"$in"=>[39620832, 219395552]}},
        options:  {},
        class:    Author,
        embedded: false>
      
      # this leads to zero results (note the ids condition is doubled)
      1.9.3p0 :031 > Author.for_ids([39620832, 219395552]).sort_fields
       => #<Mongoid::Criteria
        selector: {"$and"=>[{:_id=>{"$in"=>[39620832, 219395552]}}, {:_id=>{"$in"=>[39620832, 219395552]}}]},
        options:  {:fields=>{:_type=>1, :_id=>1, :name=>1}},
        class:    Author,
        embedded: false>
      

      However, if I put the scope dealing with ids last in the chain, everything is back to normal:

      # OK again
      1.9.3p0 :032 > Author.sort_fields.for_ids([39620832, 219395552])
       => #<Mongoid::Criteria
        selector: {:_id=>{"$in"=>[39620832, 219395552]}},
        options:  {:fields=>{:_type=>1, :_id=>1, :name=>1}},
        class:    Author,
        embedded: false>
      
      

      This bug only appears when the scope with the where condition somehow deals with the main document _id. For other fields, everything seems to be OK. Any thoughts?

      Thanks for the wonderful gem!

      Gemfile:
      gem 'rails', '3.2.1'
      gem 'mongoid', '~> 2.4'

            Assignee:
            Unassigned Unassigned
            Reporter:
            borama borama
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: