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

default_scope through has_many association in included module doesn't work

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

      I'm using Mongoid 3.0.16. Not sure if this is a bug or I'm doing something wrong.

      /app/models/bar.rb

      class Bar
         include Mongoid::Document
         include Mongoid::Timestamps
      
         has_many :foos
         include 'HasPosition'
      end
      

      /app/models/foo.rb

      class Foo
         include Mongoid::Document
         include Mongoid::Timestamps
      
         belongs_to :bar
         include 'HasPosition'
      end
      

      /app/models/concerns/has_position.rb

      require 'active_support/concern'
      module HasPosition
      
        extend ActiveSupport::Concern
      
        def included
          field :position, type: Integer
          attr_accessible :position
          validates_presence_of :position
          default_scope asc(:position)
          before_create :init_position
        end
      end
      

      Result:

      irb> Bar.first.foos.map &:position
      [2, 1, 4, 0, 3]
      

      but, Accessing Bar directly works

      irb> Bar.all.map &:position
      [1, 2, 3, 4]
      

      strangely, Accessing Foo directly doesn't work

      irb> Foo.all.map &:position
      [2, 1, 4, 0, 5, 3]
      

      However if I add to Foo

      default_scope asc(:position)
      

      Then:

      irb> Bar.first.foos.map &:position
      [0, 1, 2, 3, 4]
      

      and:

      irb> Foo.all.map &:position
      [0, 1, 2, 3, 4, 5]
      

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

              Created:
              Updated:
              Resolved: