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

Default scoped in a Module when I'm using unscoped

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

      Hi guys, firstly I would like to thank you for the great work.

      I have the following code:

      module Test
        extend ActiveSupport::Concern
        included do
          include Mongoid::Document
          field :title, :type => String
          default_scope desc :title
        end
      end
      
      class Person
        include Test
        field :name, :type => String
        scope :by_name, order_by([[:name, :desc]])
      end
      

      And I run:

      p1 = Person.create :title => "abc", :name => "abc"
      p2 = Person.create :title => "cba", :name => "cba"
      
      Person.all.to_a # [p2, p1] in order
      Person.unscoped.to_a # [p1, p2]
      
      puts Person.unscoped.by_name.inspect
      # <Mongoid::Criteria
      #  selector: {},
      #  options:  {:sort=>[[:title, :desc], [:name, :desc]]},
      #  class:    Person,
      #  embedded: false>
      

      As you can see, when I'm using unscoped included in a Module before a scope defined in a class, Mongoid does not exclude default_scope from criteria object. I had confirmed this when I ran this example:

      class Game
        include Mongoid::Document
        field :name, :type => String
        field :title, :type => String
      
        default_scope desc :title
        scope :by_name, order_by([[:name, :desc]])
      end
      
      g1 = Game.create :title => "abc", :name => "abc"
      g2 = Game.create :title => "cba", :name => "cba"
      
      Game.all.to_a # [g2, g1] in order
      Game.unscoped.to_a # [g1, g2]
      
      puts Game.unscoped.by_name.inspect
      # <Mongoid::Criteria
      #  selector: {},
      #  options:  {:sort=>[[:title, :desc], [:name, :desc]]},
      #  class:    Game,
      #  embedded: false>
      

      When I define the default_scope in a class, Mongoid works.

      Can you help me?

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

              Created:
              Updated:
              Resolved: