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

Relationship with alias_method_chain returns extra object

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

      I have a tree structure model and but looping over the children of an object, if an alias method chain is used, will return one too many objects. Doing .length will return the correct length but actually looping over the enumerable will reveal one extra object.

      Here's the model file and test script to demonstrate this behavior.

      parent = Foo.new
      child = Foo.new
      link = Foo.new
      
      child.parent = parent
      link.link_to = parent
      link.is_link = true
      
      parent.save
      child.save
      link.save
      
      puts link.children.length           # Expected to print 1 which it does
      
      link.children.each do |obj|       # Expects only 1 child, but prints 2
        puts obj.id
      end
      
      class Foo
        include Mongoid::Document
      
        has_many              :children, :foreign_key => "parent_id", :class_name => "Foo"
        belongs_to            :parent, :foreign_key => "parent_id", :class_name => "Foo"
        belongs_to            :link_to, :foreign_key => "link_id", :class_name => "Foo"
        has_many              :linked_by, :foreign_key => "link_id", :class_name => "Foo"
      
        field :is_link, :type => Boolean, :default => false
      
        def children_with_bar
          self.is_link ? self.link_to.children : self.children_without_bar
        end
      
        alias_method_chain    :children, :bar
      end
      

      I get the following output with rails 3.1.3 and mongoid 2.3.4:
      1
      4ed77ef435d3e9c4f5000002
      4ed77ef435d3e9c4f5000003

      The 1 is expected for the length but as you can see 2 id's are printed even though the length is supposedly 1.

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

              Created:
              Updated:
              Resolved: